In the last two years, due to the business needs of the company, I changed from Android development to front-end work, mainly working on Android and ReactNative. React Native, however, is a cross-platform framework with serious limitations. In short, RN is just a UI framework, and Facebook was created to use Yoga (a cross-platform UI library) to package UI code for both platforms. Once the content is non-UI, such as sensor, network, security, Permission… So RN is in a hurry.

Of course, RN is not completely impossible. What RN does is divide and conquer. It sends these things to the two native platforms to do, and then tells the results to the JS end through the bridge. This, in fact, means that programmers need to be familiar with JS, Android, and iOS development for deeper RN functions. For example, we recently made a local server that runs on mobile phones. This is obviously non-UI content, so I have to write the code on android and iOS platforms respectively (there is actually a library for react-native static-server to refer to, but we need to decrypt the content after reading it, so it is more complicated and we need to customize it by ourselves).

Such demand for native development triggers js development and Android development, so we have to learn some knowledge of iOS. Also, because the iOS code in RN is Objective-C, the language we learn is not Swift, but the older (and more anti-human) OC.

Swift 还是 OC?

As mentioned above, OC is generally used more for RN development. In particular, some special requirements, such as encryption, Swift only had crypto library in February 2020, which was not available before. These things had to be developed using OC.

Also, Swift is actually using OC underneath, like selector, so even if you’re using Swift, you still have to know something about OC.

Finally, one of the benefits of iOS development is that it can leverage the C library directly. OC can easily make use of C’s library. There are many examples

  • Thread in the GCD, in fact, is the USE of C language GCD library.
  • Unlike Java, iOS does not inherently support zip compression/decompression. OC can then make easy use of.h,.c files in libraries like MiniZip.

To sum up, this article is mainly about OC

Type in OC

Android (java) iOS (OC) js
string String NSString string
int int; Integer int; NSInteger number
map HashMap NSDictionary Object; Map
Byte array byte[] NSData ArrayBuffer

digital

Since OC is a C language, complex data types such as short, unsigned long… These types are not available in Java, so just a word.

Int I = 20; int I = 20; But we have to put an @ in OC to indicate the value in OC (not C), so the number 20 in OC is denoted as @20.

string

Char [], char[], char[], char[]. Only at sign “” means it’s an NSString, it’s a class, it’s not a char array.

The formatted output used to print logs often uses %@ as a placeholder. Such as:

NSString* name = @"xxx";
NSLog(@"hello %@", name); //=> hello xxx
Copy the code

object

Unlike In Java, objects in Java are Pointers, but you don’t have to specify them because Java doesn’t have Pointers. But Pointers are common in C – family languages. OC explicitly considers every object to be a pointer to a bunch of memory, so we define objects like this: NSString* name = @” XXX “; .

(Note that the * is a pointer.)

function

Well, this is probably the most anti-human thing about Java/JS programmers.

First the conclusion:

  • Method calls in OC are represented in brackets (as most other languages do);
  • Parameters must be accompanied by parameter description
  • Parameters are denoted by Spaces

Here’s another example:

java:

String memo = "memo.txt"; 
String extension = memo.substring(5);
Copy the code

OC:

NSString* memo = @"memo.txt";
NSString* extension = [memo substring: 5];
Copy the code

[object method:arg1 arg2Name:arg2 arg3Name:arg3]

/* declaration */ + (NSData *)decryptContent:(NSData *)encrypted withKey:(NSData *)key; 
/* usage */      [obj decryptContent: encrypted withKey: key];

/* declaration */ - (void)stop;
/* usage */       [obj stop];
Copy the code

Here withKey is the parameter name, key is the argument name. When this decryptContent method is called, it takes the parameter name except for the first parameter.

This is actually equivalent to Java

obj.decryptContent(byte[] content, byte[] key);
obj.stop();
Copy the code

The source file

Java only has “.java” and js only has “.js” files. But C languages have separate header files and implementation files. C:.h,.c OC:.h,.m

In fact,.h is a header file whose type is publicly declared in Java. All members and methods that can be accessed by external files are defined in.h.

.m is the real implementation. Some method members, which are not open to the public, can also exist in.m.

class

The OC class declaration also has two parts: interface and implementation, representing definition and implementation respectively. So interface goes into dot h so that other files can call this class. So the implementation is usually in the dot m file. Such as:

// MyClass.h
@interface MyClass: NSObject {
  NSString* name;  //property
}
-(void)hello:(NSString*)name; //method
@end
Copy the code

Note:

1). Unlike Java, you have to specify extends Object even if your class is a subclass of NSObject.

2). Class method definition, preceded by + or -.

  • + stands for static method and will be called later[MyClass func]
  • – represents a member method and is called with an object, not the class name, as in[obj func]

3). Put the return value of the method in parentheses (void).

4). The name above is the parameter. [obj hello:@”xx”];

The implementation body is:

@implementation MyClass 
-(void) hello:(NSString*)name{
  NSLog(@"hello, %@", name);
}
@end
Copy the code

namely

  • Interface has only member/method definitions, no implementation.
  • So the implementation is just writing the body of the method, what does this method actually do

category

This is a bit like Extension in Kotlin, where you can extend any class you want. Even if this class is a system class, you can extend it.

Defining a category is like defining a class, except instead of writing super Class, you use (category name) instead of the parent class name.

Here’s an example. A normal NSString does not have a UUID method. Now we add a new UUID method to the NSString, and calling this new method gives us a random UUID value.

// NSString+Uuid.h
#import <Foundation/Foundation.h>

@interface NSString (Uuid)
+ (NSString*) uuid;
@end

// NSString+Uuid.m
#import "NSString+Uuid.h"
@implementation NSString (Uuid)
+ (NSString*) uuid {
  CFUUIDRef uuidRef = ...;
  return uuidString;
}
@end
Copy the code

protocol

Protocol is an interface in Java, a collection of method definitions. OC has a.h file, but no.m file, just like Java interfaces.

@protocol ServerPlugin <NSObject>
  @required -(void) serve: (int) id;
@end


// if you want to use the protocol, use it as a generics:
@interface HttpServer: NSObject<ServerPlugin>;
@end
Copy the code

Precautions in protocol

In Java, we can use Map

. Iinterfae obj = map.get(key);
,>

In OC, a Protocol obj = [map objectForKey:key] cannot be used. Because Protocol itself is not an object at all, just an abstraction. So the correct way to write it is:

NSOjbect<某Protocol> plugin1 = [dictionary objectForKey:@"key1"];
Copy the code

Memory management

Memory management in C is manual, meaning that when you malloc requests a new block of memory, you eventually have to pay attention to free it. OC is the same way.

But Java programmers, or programmers in general, find this annoying and prone to memory leaks and problems when they forget to free references to objects. Therefore, In 2011, Apple introduced ARC(Auto Reference Counting), which automatically records the number of references for you and helps you release references when they are out of scope. This is similar to the GC in Java. OC development is finally released from the memory swamp.

Of course, you won’t have 100% automatic memory management. When you’re dealing with some C libraries, or Core Foundation frameworks, the C parts are not covered by ARC, so you still have to be careful how much memory you free up to request.

conclusion

The above are some basic knowledge points I encountered when I started OC as an Android developer, and I hope to share them with more people in need.