Objective-C Learning notes

来源:互联网 发布:济南鲁兴制衣淘宝网 编辑:程序博客网 时间:2024/06/06 11:01

There Some points in Objective-C just like NSString,NSArray,NSDictionary,Protocol,interface,abort dealing,Delegate,Listeners and more details.

At first I want to show the structure of my learning Project.:
As we can see,I have defined my own interface which are People,Man and Hi as well as I also have defined my own protocol which are IPeople and ManDelegate.
I have finished the studying of the Objective-C fundamental syntax in this simple project.
I mainly want to show some details in the supporting files.Because I haven’t used the UIKit which is the main framework for iOS.
这里写图片描述
First I can spread my introduction with the file main.m,let’s see the code of the main.m:

//  main.m//  CallMethod////  Created by 赵天宇 on 15/4/14.//  Copyright (c) 2015年 Panda. All rights reserved.#import <UIKit/UIKit.h>#import "AppDelegate.h"//#include "Hi.h"#import "People.h"#import "Hi.h"#import "Man.h"#import "ManDelegate.h"//Use the @interface to create a Objective-C class@interface Hello : NSObject{    int num;}//Define the attributes of the class.-(void)sayHello1;//create a list for methods.'-' refers to the method is public.'+'refers to the method is private.@end@interface ManListener : NSObject<ManDelegate>//define a interface for ManListener to listen the Man-class's status.Observing the protocol ManDelegate.-(void)onAgeChanged:(int)age;//because the interface observe the ManDelegate protocol , we need to achieve the method which have defined in the ManDelegate.//So we can make a conclusion that the protocol is used to limit the essential/basic foundation for a interface.@end@implementation ManListener//implement the ManListener.-(void)onAgeChanged:(int)age{    NSLog(@"Age changed,Current age is %d",age);}@end@implementation Hello//achieve the methods in the implementation area.-(instancetype)init{//this method must be quoted when we initialize the interface(in C++ we can call it class).    self = [super init];    if (self) {        num = 100;    }    return self;}//This is the init method.//if you want to get some initializations(or initialized works.),you will write some code in the  init method.-(void)sayHello1{    NSLog(@"Hello OC Class!");    NSLog(@"Num is %d",num);}@endvoid sayHello(){    printf("Hello OC!\n");}//There is a point that objective-C have the Backward compatibility to C and C++.//So we can use some C/C++ methods to solve our problems.typedef void (^HelloObjC)();//using typedef to define the CodeBlock .int (^max)(int,int);//CodeBlock;int main(int argc, char * argv[]) {//    @autoreleasepool {//        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));//    }//using the appDelegate to define a AppListener to listen the status of the application.//We can set some different works in different app's status.So the listener works for this.    People *p = [[People alloc] initWithNum:40430 andName:@"Panda"];    //achieve the attributes of the interface People by using the method I have defined in the class.    p.age = 20;//change the age of the people class.//    [p setAge:21];    sayHello();    NSString *str = [NSString stringWithFormat:@"Hello %d",100];    //Initialize the NSString *str by using the factory method.    NSLog(@"%@",str);    NSLog(@"age %d",[p age]);    sayHi();//quote the method - sayhi();    Hello *h = [[Hello alloc] init];    [h sayHello1];    NSArray *arr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];    //Initialize the NSArray with the factory method arrayWithContentsOfFile.We use a NSBundle to get the plist file.    //There is a static array whose each items can be different type in the data.plist file.    NSLog(@"p.num is %d,p.name is %@",[p getNum],[p getName]);//Using getNum and getName to print the attributes.    for (int i = 0;i < [arr count]; i++) {        NSLog(@"%@",[arr objectAtIndex:i]);    }//    NSMutableArray *arr1 = [[NSMutableArray alloc] init];//    //    for (int i = 0; i<100; i++) {//        [arr1 addObject:[NSString stringWithFormat:@"Item %d",i]];//    }//    NSLog(@"%@",arr1);    NSDictionary *dict = @{@"name":@"Panda",@"sex":@"male"};    //Initialize a NSDictionary's item.The dictionary's item's structure is Key:value couple.    NSLog(@"%@",dict);    NSLog(@"%@",[dict objectForKey:@"sex"]);    //using the factory method objectForKey to find the item whose key is "sex".    NSDictionary *dict1 = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ManData" ofType:@"plist"]];    //just like initialize the array with plist file.we can also initialize the dictionary with a plist file.    //There is a static dictionary whose each items can be different type in the ManData.plist.    NSLog(@"%@",dict1);    NSLog(@"%@",[dict1 objectForKey:@"age"]);    NSMutableDictionary *Mutabledict = [[NSMutableDictionary alloc] init];    //Initialize the Mutable Dictionary which each items can be changed as we like.    [Mutabledict setObject:@"Panda" forKey:@"name"];    NSLog(@"%@",[Mutabledict objectForKey:@"name"]);    max = ^(int a,int b){//Achieve the CodeBlock which is embedded in a function.        return a>b?a:b;    };    //I think the CodeBlock can be used slick just like a function in C.    printf("max is %d\n",max(2,3));    HelloObjC Hoc = ^(){        printf("Hello Objective-C!\n");    };//achieve the CodeBlock HelloObjC.    Hoc();    Man *m = [[Man alloc] init];//initialize the interface of the Man.    NSLog(@"%@,%d",[m getName],[m getAge]);    [m setDelegate:[[ManListener alloc] init]];//Initialize the Listener to listen the status of the man's age.    [m setAge:21];    [m setAge:20];    NSLog(@"%d",[m isKindOfClass:[NSObject class]]);    //Now we can define some abort we can use.    @try {//this is a method for the abort.        //we can define some abort we can find in this area.        @throw [NSException exceptionWithName:@"My error" reason:nil userInfo:nil];    }    @catch (NSException *exception) {        //we catch some abort in this area.if we can't catch the abort ,we can't deal with it.        NSLog(@"%@",exception);    }    @finally {        NSLog(@"run");        //This area is for the codes which deal with the abort.    }

Now there are some questions about the main.m:

  1. Where are the interfaces which include People,Man and Hi defined?
  2. Where are the protocol which include IPeople and ManDelegate
    defined?
  3. What are contents of the data.plist and ManData.plist?
  4. There are some operations that we need to see how they work.
  5. How can we achieve the Delegate?

Let us see some file in my project:

For the question 1:
People.h:

////  People.h//  CallMethod////  Created by 赵天宇 on 15/4/14.//  Copyright (c) 2015年 Panda. All rights reserved.//#import <Foundation/Foundation.h>@interface People : NSObject{    int _age;    int _num;    NSString *_name;}//define the attributes of People.+(People*)peopleWithNum:(int)num andName:(NSString*)name;//This is a factory method to deal with some thing//Use this method to convert the num and name into people.-(id)initWithNum:(int)num andName:(NSString *)name;//init the num and people.-(int)getNum;-(NSString*)getName;@property int age;@end

Hi.h:

#ifndef CallMethod_Hi_h#define CallMethod_Hi_hvoid sayHi();#endif

Man.h:

#import <Foundation/Foundation.h>#import "IPeople.h"#import "ManDelegate.h"@interface Man : NSObject<IPeople>{//Define the Man interface which observe the protocol IPeople.    int _age;}//there are the functions we need to achieve because IPeople protocol.-(id)init;-(NSString*)getName;-(int)getAge;-(void)setAge:(int)age;@property id<ManDelegate> delegate;@end

For the question 2:

IPeople.h:

#import <Foundation/Foundation.h>@protocol IPeople <NSObject>//Define the protocol in the IPeople.h .so other files can quote this protocol.-(int)getAge;-(NSString*)getName;-(void)setAge:(int)age;@end

ManDelegate.h:

#ifndef CallMethod_ManDelegate_h#define CallMethod_ManDelegate_h#endif#import <Foundation/Foundation.h>@protocol ManDelegate <NSObject>//Define the ManDelegate protocol in the ManDelegate.h.-(void)onAgeChanged:(int)age;@end

For the question 3:

data.plist
这里写图片描述
ManData.plist:
这里写图片描述

For the question 4:

People.m:

#import "People.h"@implementation People//achieve some method of people in this area.+(People*)peopleWithNum:(int)num andName:(NSString *)name{//achieve factory method in there.    return [[People alloc] initWithNum:num andName:name];}-(instancetype)initWithNum:(int)num andName:(NSString *)name{    self = [super init];    if (self) {        _num = num;        _name = name;    }    return self;}-(void)setAge:(int)age{//iOS system have generated methods - "setter" and "getter"    //in this way , we can rewrite it by ourself to reduce some useless operations.    NSLog(@"Set age");    _age = age;}-(int)age{    NSLog(@"Get age");    return _age;}-(int)getNum{    return _num;}-(NSString*)getName{    return _name;}@end

Man.m:

#import "Man.h"@implementation Man//this is the implementation of the Man interface.-(instancetype)init{    self = [super init];    if (self) {        self.delegate = nil;//at first the Listener is nil to wait for some changes.        _age = 20;    }    return self;}-(int)getAge{    return _age;}-(NSString*)getName{    return @"Panda";}-(void)setAge:(int)age{    if (age!=_age) {        if (self.delegate) {//if we find the age is changed we can set a message to the application.            [self.delegate onAgeChanged:age];            //if the message is sent successfully,We can say the ManListener is built successfully.        }    }    _age = age;}@end

For the question 5:

if we are willing to use delegate to build a listener to listen the status of the p.ages,first we need to define a protocol-ManDelegate to limit the ManListener interface.In order to achieve the ManListener ,we need to obey the rule of ManDelegate.So we have to the function onAgeChanged:(int)age{} when @implementation ManListener.
Now everything has been readied for the ManListener. So we can use ManListener to listen the status of p.age.When the age is changed,ManListener will send a message.

0 0
原创粉丝点击