IOS Development Review notes (1)-Basic OC knowledge, ios-oc

Source: Internet
Author: User

IOS Development Review notes (1)-Basic OC knowledge, ios-oc

I have been studying IOS for more than three months since I went to work. Because of the weak foundation, I learned from the basic syntax of OC and read the books of grapefruit and grapefruit one after another, now I am looking at the actual programming practice. take this opportunity to make a good summary:

1. Naming Conventions

Object Type and name are consistent to avoid confusion

-(Void) setURL :( NSString *) URL; // incorrect naming method // change to-(void) setURLString :( NSString *) string;-(void) setURL: (NSURL *) URL;

Static variables (including scopes) start with s, and the complete set variables start with g. Generally, global variables other than constants should be avoided:

static MYThing *sSharedInstance

Constants start with k in Cocoa and Core Foundation, but not in Cocoa. We recommend that all static constants in the File Scope start with k:

static const NSUInteger kMaximumNumberOfRows=3;NSString *const MYSomethingHappenedNotification=@"SomethingHappeded";

A naming post (a, an, the) is usually added to the method parameter name. (Note: This is not very common ), this method can be used to name parameters to avoid confusion with local variables and instance names in the method.

Instance variables start with an underscore

The class name must start with an uppercase letter. The method name and variable name must start with a lowercase letter. All class names must be case-insensitive (that is, the first letter of each word is case-insensitive, do not use underscores

2. Automatic Reference count

ARC is not garbage collection, it is just a compiler optimization, so it cannot handle the issue of loop reference:

 

Garbage collection mechanism if the reference link from an external object to object A is interrupted, object A and object B will be destroyed, but because of the mutual reference of A and B in ARC, the reference count is greater than 1. Therefore, you must manage strong references in IOS development.

There are two main types of attribute relationships: strong and weak, which are equivalent to retain and assign in a non-ARC environment. As long as a strongly referenced object exists, it will always exist and will not be destroyed. When the referenced object is destroyed, the weak reference is automatically set to nil. Therefore, the delegate attribute should always be declared as weak.

3. Attributes

Declare the public attribute in the header file and the private attribute in the. m file:

//MyClass.h@interface class: NSObject@property (nonatomic,readwrite,weak) id delegate;@property (noatomic,readonly,strong) NSString *readonlyString;
@end//MyClass.m@interface MyClass() @property (noatomic,readwrite,strong) NSString *readonlyString;@property (noatomic,strong) NSString *privateString;
@end

 

The compiler automatically creates several variables, including _ delegate, _ readonlyString, and _ privateString. However, you can only call these instance variables in init and dealloc.

In addition, we can see that the readonlyString variable is redefined in the. m file, and a private setter method is added for it.

Attribute modifier keywords:

1) atomicity (atomic, nonatomic)

It means that the accessor method of the attribute is thread-safe and does not guarantee that the entire object is thread-safe. For example, to declare a stuff using NSMutableArray, use

Self. stuff and self. stuff = otherstuff (only access is involved). It is not thread-safe to access the Array Using objectAtIndex.

However, if the attribute does not require access from other threads, it is a great waste to use the atomic attribute. Therefore, nonatomic is usually used.

2) read/write attributes (readwrite and readonly)

3) set the key words for method modification (weak, strong, copy)

Note that copy is used for immutable classes such as NSString and NSArray.

Attributes are used to indicate the object state. The getter method must have no external side effects, so the execution speed is fast and there should be no blocking.

 

Attributes and private instance variables. You can use private instance variables in @ implementation.

For example, @ implementation {

NSString * _ name;

}

The default storage type is strong.

4. Memory

Some scopes used, or the accessors must be used instead of instance variables:

KVO (Key-Value Observing)

Attributes can be automatically observed. When modifying an attribute, you can call willChangeValueForKey: And didChangeValueForKey: method.

Side effects (the landlord is not very familiar with side effects)

Class or subclass may reference side effects in the set method. There may be some notifications or events registered with NSUndoManager, which should not be ignored unless necessary. Similarly, classes or child classes may use caching in obtaining methods, but directly accessing instance variables will not use caching.

Lock

Using instance variables directly in multi-threaded code will break through the lock mechanism.

Memory should not be used:

Memory

Dealloc Method

Initialization Method: here we can use _ Value instead of attribute.

 

5. Classification and Expansion

In my opinion, category is relatively easy to use. Reduces inheritance and adds new methods to existing classes, similar to the extension method in C #.

Classification is used to modularize a large class into multiple classes that are easy to maintain.

The classification Declaration is very simple and similar to the interface. You just need to write the classification name in the parentheses after the class name:

@ Interface NSMutableString (Capitalize)

-(Void) capitalize

@ End

Capitalize is the name of the category. Technically speaking, the method can be overwritten in a category, but this is not recommended. If two categories contain methods of the same name, it is impossible to predict which method will be used.

The rational use of classification is to add some applicable methods for existing classes. Use the original class name + category name as the name of the new header file and implementation file.

For example, add a simple classification of MyExtensions for NSDate:

//NSDate+MyExtensions.h@interface NSDate(MyExtensions)-(NSTimeInterval) timeIntervalUntilNow;@end;//NSDate+MyExtensions.m@implementation NSDate(MyExtensions)-(NSTimeInterval) timeIntervalUntilNow{    return [self timeIntervalSinceNow];}@end

If you only want to add a few methods to use, the better way is to put these methods in the MyExtensions class, but you need to weigh to prevent code expansion.

Join reference to add data for classification

You cannot create instance variables in a category, but you can create association references to add key-value data to any object through association references.

Because attributes cannot be merged in a category,

For example

// Person class, and add an email @ interface Person: NSObject @ property (nonatomic, copy) NSString * name; @ end; @ implementation Person @ end; // Add a category # import <objc/runtime. h> @ interface Person (emailAdress) @ property (nonatomic, copy) NSString * emailAdress; @ end; // if so, an error occurs when the attribute cannot be obtained or copied during reference or replication. // The attribute cannot be merged in the category. // @ implementation Person (emailAdress) // @ end; // correct practice @ implementation Person (emailAdress) static char emailAdressKey;-(NSString *) emailAdress {return objc_getAssociateObject (self, & emailAdressKey);}-(void) setEmailAdress :( NSString *) emailAdress {objc_setAssociateObject (self, & emailAdressKey, emailAdress, OBJC_ASSOCIATE_COPY);} @ end;

We can see that the associated reference is a key-based memory address, not a key value.

If a related object is attached to the warning panel or warning control, using Correlated references is a good form.

Objc_setAssociatedObject (<# id object #>, <# const void * key #>, <# id value #>,< # objc_AssociationPolicy #>) // (target class instance, associated reference key, associated reference value
, Copying, assigning, and retaining semantics)
Objc_getAssociatedObject (<# id object #>, <# const void * key #>) // (target class instance, associated with the reference key)
#import "ViewController.h"#import <objc/runtime.h>@implementation ViewControllerstatic const char kRepresentedObject;- (IBAction)doSomething:(id)sender {  UIAlertView *alert = [[UIAlertView alloc]                        initWithTitle:@"Alert" message:nil                        delegate:self                        cancelButtonTitle:@"OK"                        otherButtonTitles:nil];  objc_setAssociatedObject(alert, &kRepresentedObject,                            sender,                           OBJC_ASSOCIATION_RETAIN_NONATOMIC);  [alert show];  }- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {  UIButton *sender = objc_getAssociatedObject(alertView,                                               &kRepresentedObject);  self.buttonLabel.text = [[sender titleLabel] text];}@end

Class Extension

It can be regarded as an anonymous class of category on the Internet, and attributes can be freely declared. However, the declared method must be implemented in implementation.

6. Protocol

Declare an agreement

@ Protocol name <NSObject>

@ Required

// Required

@ Optional

// Select the implemented

Protocols can be inherited like classes. Protocols always inherit <NSObject>. NSObject is divided into one class and one protocol.

Delegate protocol (delegate protocol)

The first parameter is the delegate object, so that one delegate can manage multiple delegate objects.

After creating a protocol, you also need an attribute for easy operation.

@ Property (nonatomic, weak) id <Mydelegate> delegate;


Where are ios study notes? Is it suitable for self-developed ios?

If you do not need to enter the training institution, you can learn it. If you do not need to pay the money, you must learn it. However, it depends on whether you have the self-control ability.
IOS applications are 1.4 times more than Android, while system developers are 0.38 times more than Android. This shows that the talent gap in the iOS industry is quite large. Because of this, the market is extremely pressing for Objective-C and C ++ developers, making the two occupations quite positive in employment trends, finally, it pushed the iOS industry to stride into the sunrise industry. In the current market environment that is in short supply, the increase in iOS talent salary is much higher than that of Android.

The next 10 years will be the mobile Internet era. This conclusion has become a consensus in the industry.
1: deploying iOS applications is a required strategic choice for enterprises.
2: the involvement of large enterprises will aggravate the shortage of iOS Talents
3: Code workers are rejected in the iOS field. The so-called experts are not only proficient in technology, but also understand users, the market, and design. The iOS field is dominated by compound and innovative talents.
 
What is the basis for learning ios development? Help me to recommend some materials,

You can use Baidu's IOS developer blog. The above content is comprehensive. If you have several years of development experience, you can learn by yourself. If not, it is very difficult to learn by yourself.
The basic process is c → oc → UI → several small projects (Be sure to do)
C language does not need to be learned too finely. c has not been learned for a year or two, and it is mainly used to establish a programming idea. Get started with iphone development. In addition, Stanford University's video course also exists in that blog.

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.