Learn iOS (1) ObjectC syntax with me

Source: Internet
Author: User

Preface:
Why do you want to learn with me? I have set a direction from the beginning to write this series of blogs. Instead of talking about the basics, I chose some other languages (C, C #, Java, Javascript, etc) where programmers are prone to errors.

Suppose you have several years of development experience in other languages and have a good understanding of the above basic languages. This is what I wanted most people to tell me when I first learned this language.

 

Unique @ symbol

First, ObjectC is the superset of C. In order not to conflict with the existing items in C, all the special items in ObjectC are preceded by the @ symbol.

For example, to declare a string, you can declare it as a C-type string.

char *name = "langxue";

The declared string is not an ObjectC object, so it does not carry some specific methods. The literal string in ObjejctC is declared in this way.

NSString *name = @"langxue"

 

 

Syntax differences

I. Method Name

The method name in ObjectC consists of multiple segments.

For example, we want to initialize a controller. The most common method is this method.

InitWithNibName: bundle:

It looks strange, right? The method signature is as follows:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

The parameters are followed by the called predicates, which seem to be more in line with the natural syntax. Even if there are multiple parameters, it is easy to remember.

Brackets:

A bracket represents a call and looks clear.

The specific call is as follows:

[[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];

We first allocated a piece of memory based on the size required by the MyViewController class, and then sent messages to initialize this piece of memory.

Because the method name includes: symbol, when selecting a method through selector, the symbol cannot be forgotten.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

 

Ii. id

This is similar to the general pointer void * in C, which can be used to store any class object. Similar to the dynamic keyword in C #, the compiler does not need to check the type of the variable during compilation, and then checks and determines when running the variable. In other words, it is dynamic binding. Because the object always carries the isa pointer, even if we cannot get information from the pointer type, we can always get the type information from the object itself.

Where can it be used in ObjectC?

1. during initialization

ObjectC an object cannot have two methods with the same name, even if their parameters and return types are different. Therefore, the init method of the subclass cannot return the subclass; otherwise, the same init method of the parent class cannot be called, and the parent class cannot be returned.

In this case, the generic pointer id is used.

2. No specific type is required. You only need to know that this instance has implemented some methods. Similar to the interface programming in C #, the delegate attribute is often declared to provide objects using different policies.

@property (nonatomic, weak) id<RequestDelegate> delegate;

 

It should be noted that although it can store any class object, if it is abused, it will lose the benefit provided by the compiler when the static type is used.

Iii. strong/weak references (strong, week (ARC); retain, assign (non-ARC ))

Whether to add a reference count. There is no automatic garbage collection mechanism in iOS, and garbage collection is determined by reference count. When the reference count of an object is 0, it is considered that the garbage is destroyed immediately, which is different from the garbage collection delay of the GC mechanism. Memory can be used more efficiently.

In the ARC Project

@property (strong, nonatomic) MyController *myController;

 

 

4. protocol)

Similar to the Interface in C #, the difference is that the methods defined in protocol can be optional and do not need to be implemented, that is, @ optional. Of course, if there is no tag, it must be implemented.

@protocol BoardActionDelegate<NSObject>@required- (void) selectPressed:(UIView *)sender;@optional- (void) cancelPressed:(UIView *)sender;@end

 

5. Category)

1. The naming category is similar to the extension method in C #. It is used to extend custom methods to existing classes. The difference is that ObjectC does not limit the type of methods, such as instances or class methods. But it cannot contain member variables.

For example, we can extend the UIColor class.

@interface UIColor (Extract)- (void)extract_getRed;       @end

It is best to name such files as the original class name + extension class name, such as UIColor + Extract. h, UIColor + Extract. m

2. class extension looks like a category without a name. It can contain variable members and must be implemented.

Based on good code division, the methods and attributes I want to put in the header file. h are usually open to the public, and the private methods I use internally do not need to be placed in the header file. In a language without header files such as C #, We will write the Public method according to the Conventions, and then mark it with # region for convenience.

Suppose we have a CarStock class in CarStock. m has the following code, so this problem will occur. If the method declaration called in init is under the init position, the compiler will report an error because it is parsed from top to bottom.

- (id)init {        if ((self = [super init])) {            [self refreshStock];        }       return self;    }- (void)refreshStock {      // ...  }

There are several solutions

1. Move the refreshStock method up

2. The refreshStock statement is in the header file CarStock. h.

However, none of these comply with my idea of writing a private method. Methods In ObjectC do not contain scope declarations, that is, you cannot declare them as follows:

Private-(void) refreshStoc

Therefore, in CarStock. m, a nameless category can be used to solve this problem.

@interface CarStock ()- (void)refreshStock;       @end

 

6. @ dynamic
Tell the compiler that this attribute will generate the corresponding get and set Methods elsewhere (in ObjectC, the attribute is synthesized by the @ synthesize (synthesis) keyword)

This attribute is synthesized in Super class:

@property (nonatomic, retain) NSButton *someButton;...@synthesize someButton;

If Subclass does not synthesize * someButton or provides the get and set methods, the compiler will prompt a problem:

@property (nonatomic, retain) IBOutlet NSButton *someButton;...@dynamic someButton;

We want to use the synthesis method in Super class to synthesize Subclass. At this time, we can use the @ dynamic keyword to disable the compiler warning.

This is rarely used in Common Code and is often used in the use of Core data (ORM framework in ObjectC. We inherit NSManagedObject and want it to complete the corresponding accessors method.

 

VII. @ class

In the header file. h, we often do not need to know the specific method information of the referenced class, but just need to know that there is such a class, so that we can declare the variable type, at this time, we can replace # import with the @ class keyword, which tells the compiler that we will certainly have such a class and you don't have to check it. In this way, compilation speed can be accelerated in some large projects. It can also solve the possible problems caused by circular import.
The header file required for import in. m is used.

 

8. nil
Nil is similar to null. The difference is that it does not produce errors when sending messages to nil. The default Implementation of nil is to ignore this information. Errors similar to NullReference are generated in C # and other languages.

The reason is that nil does not include the self pointer in the implementation of the underlying C. If the detection self is null when the selector is called when the message is sent, the system returns the result directly.

When using NSError, we usually check whether NSError is nil to determine whether a method call has an error.

        NSError *error = nil;        self.responseString = [NSString stringWithContentsOfFile:zipFileName_ encoding:NSUTF8StringEncoding error:&error];        if (error)

In addition, you can set unused variables to nil in the dealloc method to prevent errors caused by pointer pointing to invalid memory after release.

Some new syntactic sugar added by the compiler after Xcode 4.4 (LLVM4 compiler)

Xcode is free, so we can upgrade to the new version to enjoy some of the benefits of the new compiler.

1. more literal support

It turns out that when we create an NSString object in ObjectC, we can

NSString *myName=@"langxue";

Now we can use the literal syntax to create other objects.

NSNumber *myNumber =@3;NSNumber *yesValue =@YES;NSArray *array =@[@1,@2,@3,@4];NSDictionary *dictionary =@[@"key1":@"value1"                  ,@"key2":@"value2"]

 

2. subscript access

We can directly access the elements we need through subscript, which is not possible in the past.

int element3 = array[3]; int elementAt3 = dictionary [@"key3"]

 

3. Automatically synthesize @ property

After property is declared

@property (strong, nonatomic) MyController *myController;@property (nonatomic, copy) void (^completionHandler)();

In the past, the accessors were synthesized by the @ synthesize keyword.

@synthesize myController = _myController;
@synthesize completionHandler = _completionHandler;

With the new LLVM compiler, You can omit the code used to synthesize instance variables. The LLVM 4 compiler will automatically synthesize these instance variables. Of course, if you explicitly write the get and set methods, LLVM 4 will not automatically generate the @ synthesize command. Remember that the automatically merged instance variables start with an underscore _ following the conventions in ObjectC.

 

Finally, if you think this article is helpful, click the lower right corner to recommend it. This is my motivation to continue. Thank you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.