objective c基础入门练习
2014-04-25 21:25
501 查看
包含基础数据类型,set集合,dictionary,数组,面向对象编程,异常处理,block块,category,和一些新式写法
main.m
MyClass.h
MyClass.m
MyClass2.h
MyClass2.m
Persion.h
Persion.m
Student.h
Student.m
StudentExt.h
StudentExt.m
CustomException.h
CustomException.m
Box.h
Box.m
CustomException2.h
CustomException2.m
附:创建测试工程
main.m
// // main.m // TestOC // // Created by YangXuan on 14-4-22. // Copyright (c) 2014年 YangXuan. All rights reserved. // #import <Foundation/Foundation.h> #import "MyClass.h" #import "MyClass2.h" #import "Persion.h" #import "Student.h" #import "StudentExt.h" #import "Box.h" void test1(){ //MARK: ==test base @autoreleasepool { MyClass* my=[[[MyClass alloc] init] autorelease]; NSString* str=@"hello world"; [MyClass staticMethod:str]; [my aaa:100]; NSString* str3=[my bbb:19 :@"yang" :@"wilker"];//传递多个参数 NSLog(@"str3 is %@",str3); NSString* str4=[my ccc:19 two:@"yang222" three:@"wilker"];//根据标识符传递参数 NSLog(@"str4 is %@",str4); //setter进去 [my setMyStr:@"asdfasdf"]; //getter出来 NSString* str6=[my myStr]; NSLog(@"myString is %@",str6);//myString is asdfasdf NSString* strtmp; NSString* str1=@"str1"; NSString* str2=@"str2"; strtmp=[NSString stringWithFormat:@"%@ ... %@",str1,str2];//创建格式化字符串 NSLog(@"%@",strtmp);//str1 ... str2 //定义可变字符串,往后面追加字符串 NSMutableString* str7=[NSMutableString stringWithString:@"hello"]; [str7 appendString:@" Mr. Yang"]; NSLog(@"%@",str7);//hello Mr. Yang } } void test2(){ //MARK: ==测试retain、copy区别,两个都需要release @autoreleasepool { MyClass2* my2=[[[MyClass2 alloc] init] autorelease]; NSMutableString* str1=[NSMutableString stringWithString:@"wer"]; my2.str2=str1; [str1 appendString:@" oioi"]; NSLog(@"my2.str2 is %@",[my2 str2]);//my2.str2 is wer //解释:str2成员变量是copy属性,拷贝了副本,所以str1变化不跟着变化 NSMutableString* str2=[NSMutableString stringWithString:@"wer"]; my2.str3=str2; [str2 appendString:@" oioi"]; NSLog(@"my2.str3 is %@",[my2 str3]);//my2.str3 is wer oioi //解释:str3成员变量是retain属性,会跟着输入源变化而变化,所以str1变化会跟着变化 } } void testArray(){ @autoreleasepool { //MARK: ==定义可变数组 // [NSMutableArray arrayWithCapacity:6] :初始化可变数组对象的长度,如果后面代码继续添加数组超过长度6以后NSMutableArray的长度会自动扩充,6是自己可以设置的颗粒度。 // [array addObject:...] : 向可变数组尾部添加数据对象。 // [array addObjectsFromArray:..] :向可变数组尾部添加一个数组对象。 NSMutableArray* array1=[NSMutableArray arrayWithCapacity:5]; [array1 addObject:@"hello"]; [array1 addObject:@"world"]; [array1 addObject:@"Mr. Yang"];//都是插在末尾 NSLog(@"array1 count is %lu",array1.count);//array1 count is 3 NSLog(@"第一种遍历方法:"); //第一种遍历方法: for (int i=0; i<array1.count; i++) { NSLog(@"%@",[array1 objectAtIndex:i]); } [array1 insertObject:@"two" atIndex:1]; //插入索引为几的位置,原来位置以后的对象往后顺推一位; //移除最后一个元素 [array1 removeLastObject]; NSLog(@"第二种遍历方法:"); //第二种遍历方法:快速枚举 for(NSString* str in array1){ NSLog(@"%@",str); } //根据索引移除对应元素 // [array removeObject:(id)] :删除数组中指定元素,根据对象isEqual消息判断。 // [array removeObjectIdenticalTo:(id)] : 删除数组中指定元素,根据对象的地址判断 // [array removeObjectIdenticalTo:(id) inRange:(NSRange)] : 在指定范围内删除指定的元素。 // [array removeObjectAtIndex:(NSUInteger)]:删除数组中指定脚标索引的数据。 // [array removeObjectsInArray:(NSArray *)] :删除一个数组的元素。 [array1 removeObjectAtIndex:0]; NSLog(@"第三种遍历方法:"); //第三种遍历方法:迭代器 id ob; NSEnumerator* enumerator=[array1 objectEnumerator];//实现一个迭代器 while (ob=[enumerator nextObject]) { NSLog(@"%@",ob); } NSLog(@"--------------------------------------------"); //定义可变数组 NSMutableArray* array2 = [NSMutableArray arrayWithArray:array1]; NSLog(@"%lu",array2.count); //定义不可变数组 // NSMutableArray* array3=[NSMutableArray arrayWithObjects:@"a1",@"a2",@"a3", nil]; NSArray* array3=@[@"a1",@"a2",@"a3"]; NSLog(@"%lu",array3.count); //字符串分割成数组对象与连接 NSString* str3=@"one,two,three,four,five"; //MARK: ==不可变数组,将nsstring分割成数组,以 , 分割 // [array count] : 数组的长度。 // [array objectAtIndex 0]: 传入数组脚标的id 得到数据对象。 // [arrayWithObjects; ...] :向数组对象初始化赋值。这里可以写任意对象的指针,结尾必须使用nil。 NSArray* array4=[str3 componentsSeparatedByString:@","]; for(NSString* str in array4){ NSLog(@"%@",str); } //将数组组装成nsstring,以@@隔开 NSString* str4=[array4 componentsJoinedByString:@"@@"]; NSLog(@"%@",str4);//one@@two@@three@@four@@five } } void testNumberAndValue(){ //MARK: ==NSArray可以放一切数据,除了C中的基本数据类型,C中的一些基本元素我们可以用NSNumber类来包装,类似java中的装箱,另外还有一些struct类型的数据我们也可以用NSNumber类的父类NSValue来进行包装,包装成NSValue的对象再将其放入数组中。具体使用方法看代码: int age=323; char c='s'; float f=3.14f; NSRect rect=NSMakeRect(1, 2, 3, 4); NSNumber* myAge=[NSNumber numberWithInt:age]; NSNumber* myC=[NSNumber numberWithChar:c]; NSNumber* myF=[NSNumber numberWithFloat:f]; NSValue* myRect=[NSValue valueWithRect:rect]; NSArray* array1=[NSArray arrayWithObjects:myAge,myC,myF,myRect, nil]; for (int i=0; i<array1.count; i++) { NSLog(@"%@",[array1 objectAtIndex:i]); } } void testSet(){ //MARK: ==不可变集合 // [NSSet setWithSet:(NSSet *)set]; 用另外一个set对象构造 // [NSSet setWithArray:(NSArray *)array];用数组构造 // [NSSet setWithObjects:...]:创建集合对象,并且初始化集合中的数值,结尾必需使用nil标志。 // [set count] ; 得到这个结合对象的长度。 // [set containsObject:...]: 判断这个集合中是否存在传入的对象,返回Bool值。 // [set objectEnumerator]: 将集合放入迭代器。 // [enumerator nextObject]:得到迭代器中的下一个节点数据,使用while遍历这个迭代器,方可遍历集合对象中的对象。 // [set isEqualToSet:objset]:判断两个集合是否完全相等,返回Bool值。 // [set isSubsetOfSet:objset]:判断集合中的所有数据是否都相等与objeset集合中,返回Bool值。 // [set allObjects]; NSNumber* num=[NSNumber numberWithInt:189]; NSString* str=@"hello world"; NSSet* set1=[NSSet setWithObjects:num,str, nil]; //集合数量 NSLog(@"%lu",[set1 count]); //是否包含 NSString* str2=@"hello world"; if ([set1 containsObject:str2]) { NSLog(@"集合中包含 %@ 这个对象",str2); } //迭代器遍历 NSLog(@"迭代器遍历"); NSEnumerator* em=[set1 objectEnumerator]; id object; while (object=[em nextObject]) { NSLog(@"%@",object); } //快速枚举遍历 NSLog(@"快速枚举遍历"); for(NSObject* ob in set1){ NSLog(@"%@",ob); } } void testMutableSet(){ //MARK: ==可变集合 // NSMutableSet继承NSSet,它可以使用NSSet的方法。 // [NSMutableSet setWithCapacity:6]:创建可变集合对象,并且初始化长度为6。 // [set addObject: obj] : 向集合中动态的添加对象。 // [set removeObject:obj]:删除集合中的一个对象。 // [set removeAllObjects]:删除集合中的所有对象。 // [set unionSet:obj]:向集合中添加一个obj集合的所有数据。 // [set minusSet:obj]:向集合中删除一个obj集合的所有数据。 // [set intersectSet]:向集合中删除一个不包含obj集合的所有数据。 NSMutableSet* set2=[NSMutableSet setWithCapacity:10]; [set2 addObject:@"hello world"]; [set2 addObject:[NSNumber numberWithInt:234]]; NSString* str=@"yang"; [set2 addObject:str]; for(NSObject* obj in set2){ NSLog(@"%@",obj); } //删除对象 [set2 removeObject:str]; NSEnumerator* em =[set2 objectEnumerator]; id obj; while(obj=[em nextObject]){ NSLog(@"%@",obj); } } void printfForDic(NSDictionary* dic){ //遍历键值对 NSEnumerator* em=[dic keyEnumerator]; for(NSObject* obj in em){ NSObject* value=dic[obj]; NSLog(@"key:%@ , value:%@",obj,value); } } void testDicitonary(){ //MARK: ==test Dictionary @autoreleasepool { //不可变Dictionary // [NSDictionary dictionaryWithObjectsAndKeys:..] : 使用键值对直接创建词典对象,结尾必需使用nil标志结束。 // [dictionary count]: 得到词典的键值对数量。 // [dictionary keyEnumerator]: 将词典的所有key储存在NSEnumerator中,类似于Java语言中的迭代器 // [dictionary objectEnumerator]: 将词典的所有value储存在NSEnumerator中 // [dictionary objectForKey:key]: 通过传入key对象可以拿到当前key对应储存的值。 NSDictionary* dic=@{@"25":@"age",@"张三":@"name",@"男":@"性别"}; NSLog(@"%lu",[dic count]); //遍历key NSEnumerator* emkey=[dic keyEnumerator]; for(NSObject* obj in emkey){ NSLog(@"key:%@",obj); } //遍历value NSEnumerator* emobject=[dic objectEnumerator]; for(NSObject* obj in emobject){ NSLog(@"value:%@",obj); } //遍历key value,根据key获取value printfForDic(dic); //可变Dictionary // NSMutableDictionary是NSDictionary的子类,所以继承了NSDictionary的方法, 以上的代码对NSMutableDictionary来说完全可用。我们试试不一样的地方 // 增删键值数据。 // [dictionary setObject: forKey:] :向可变的词典动态的添加数据 // [dictionary removeAllObjects..] : 删除掉词典中的所有数据。 // [dictionary removeObjectForKey..] :删除掉词典中指定key的数据 NSLog(@"可变Dictionary"); NSMutableDictionary* dicMu=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"25",@"age",@"张三",@"name",@"男",@"性别",nil]; //添加键值对 // [dicMu setObject:@"20名" forKey:@"名次"]; // [dicMu setValue:@"30名" forKey:@"名次2"]; dicMu[@"名次"]=@"20名"; dicMu[@"名次2"]=@"30名"; printfForDic(dicMu); //删除键值对 [dicMu removeObjectForKey:@"名次"]; printfForDic(dicMu); } } void test4(){ //MARK: ==retainCount test MyClass2* my2=[[MyClass2 alloc] init]; NSLog(@"%lu",(unsigned long)[my2 retainCount]); NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; [my2 autorelease]; NSLog(@"%lu",(unsigned long)[my2 retainCount]); [my2 retain]; [my2 retain]; NSLog(@"%lu",(unsigned long)[my2 retainCount]); [pool release]; NSLog(@"%lu",(unsigned long)[my2 retainCount]); } void testStringConvertInteger(){ //MARK: ==NSString与NSInteger的相互转换 NSInteger aaa=988; NSString* str=[NSString stringWithFormat:@"%ld",(long)aaa]; NSLog(@"string is %@",str); NSInteger bbb=[str integerValue]; NSLog(@"%ld",bbb); } void testNSString(){ //MARK: ==指向相同的地址,文字常量区 NSString* a=@"hello"; NSString* b=@"hello"; BOOL bo=a==b; if (bo) { NSLog(@"address:%p", a); NSLog(@"address:%p", b); } } void testCustomConstruct(){ //MARK: ==自定义构造方法 MyClass2* my2=[[MyClass2 alloc] initCustom:@"yang" :109]; NSLog(@"name is %@, age is %ld",[my2 name],[my2 age]); } void testIsMemberOfClass(){ //MARK: ==动态类型(isKindOfClass, isMemberOfClass,id)等 Persion* person = [[Persion alloc] init]; if ([person isMemberOfClass:[Persion class]]) { NSLog(@"person is Persion类的成员"); } if ([person isKindOfClass:[MyClass class]]) { NSLog(@"person is MyClass类的子类"); } if ([person isKindOfClass:[NSObject class]]) { NSLog(@"person is NSObject类的子类"); } if ([person respondsToSelector:@selector(setName:)]) { NSLog(@"person responds to setName: method"); } } void testKVC(){ //MARK: ==除了一般的赋值和取值的方法(setter getter),我们还可以用Key-Value-Coding(KVC)键值编码来访问你要存取的类的属性。 @autoreleasepool { Student* stu=[[[Student alloc] init] autorelease]; [stu setValue:@"yang" forKey:@"name"]; NSString* name=[stu valueForKey:@"name"]; NSLog(@"%@",name); } } void testBlock(){ //MARK: ==代码块(block)的使用 void (^printBlock)(NSString* x); printBlock = ^(NSString* str){ NSLog(@"print:%@",str); }; printBlock(@"hello world"); int (^myBlock)(int) = ^(int num){ num++; return num*100; }; int result = myBlock(7); NSLog(@"%d",result); //代码用在字符串数组排序 NSArray *stringArray = [NSArray arrayWithObjects:@"abc 1", @"abc 21", @"abc 12",@"abc 13",@"abc 05",nil]; NSComparator sortBlock = ^(id string1, id string2) { return [string1 compare:string2]; }; NSArray *sortArray = [stringArray sortedArrayUsingComparator:sortBlock]; NSLog(@"sortArray:%@", sortArray); //而局部变量可以使用,但是不能改变。 //在代码块中改变局部变量编译不通过。怎么在代码块中改变局部变量呢?在局部变量前面加上关键字:__block __block int local =200; void(^block)(void) = ^(void) { local++; NSLog(@"local:%d", local); }; block(); NSLog(@"local:%d", local); } void testCategory(){ //MARK: ==Category的使用 @autoreleasepool { Student* stu=[[[Student alloc] init] autorelease]; [stu myPrint]; [stu hello]; } // 那的Category的使用场景有那些呢: // 1、类包含了很多个方法实现,而这些方法需要不同团队的成员来实现 // 2、当你在使用基础类库中的类时,你不想继承这些类而只想添加一些方法时。 // // Category能实现上面的需求,当然也有使用Category是需要注意的问题: // 1、Category可以访问原始类的实例变量,但不能添加实例变量,如果想添加变量,那就通过继承创建子类来实现。 // 2、Category可以重载原始类的方法,不大不推荐这么做,这样会覆盖掉原始类的方法。如果确实要重载,那就通过继承创建子类来实现。 // 3、和普通接口有所区别的是,在Category的实现文件中的实例方法只要你不去调用它你可以不用实现所有声明的所有方法。 } void testNewFeature(){ //MARK: ==新式写法 NSNumber* num2=@123; NSNumber* num3=@'y'; NSNumber* num4=@12345ul; NSNumber* num5=@12345ll; NSNumber* num6=@123.45f; NSNumber* num7=@YES; NSLog(@"%@",num2); NSLog(@"%@",num3); NSLog(@"%@",num4); NSLog(@"%@",num5); NSLog(@"%@",num6); NSLog(@"%@",num7); NSArray* arr=@[@"asdf",@123,@YES]; NSLog(@"%@",arr); NSDictionary* dic=@{@"key1":@"value1", @"key2":@"value2" , @"key3":@"value3"}; NSLog(@"%@",dic); } void testException(){ //MARK: ==自定义异常 @autoreleasepool { Box* box=[[[Box alloc] init] autorelease]; for (int i=0; i<11; i++) { @try { [box pushIn]; } @catch (NSException *exception) { NSLog(@"%@ , %@",[exception name],[exception reason]); } @finally { [box printNumber]; } } @try { [box setMyNum:-18]; } @catch (NSException *exception) { NSLog(@"%@ , %@",[exception name],[exception reason]); } @finally { [box printNumber]; } } } int main(int argc, const char * argv[]) { testStringConvertInteger(); return 0; }
MyClass.h
#import <Foundation/Foundation.h> @interface MyClass : NSObject{ } @property (nonatomic,copy) NSString* myStr; +(void) staticMethod:(NSString*) str; -(void) aaa:(int) i; -(NSString*) bbb:(int)i :(NSString *)str :(NSObject *)obj; -(NSString*) ccc:(int)i two:(NSString *)str three:(NSObject *)obj; @end
MyClass.m
#import "MyClass.h" @implementation MyClass{ } //静态方法 +(void) staticMethod:(NSString*) str{ NSLog(@"the string is %@",str); } //非静态方法,无返回值, -(void) aaa:(int)i{ NSLog(@"the integer is %d",i); } //非静态方法,有返回值,多参数 -(NSString*) bbb:(int)i :(NSString *)str :(NSObject *)obj{ NSLog(@"i=%d , str=%@ , obj=%@ ",i,str,obj); return [NSString stringWithFormat:@"return string is %@",str]; } //非静态方法,有返回值,多参数,two和three标示符, -(NSString*) ccc:(int)i two:(NSString *)str three:(NSObject *)obj{ NSLog(@"i=%d , str=%@ , obj=%@ ",i,str,obj); return [NSString stringWithFormat:@"return string is %@",str]; } @end
MyClass2.h
#import <Foundation/Foundation.h> @interface MyClass2 : NSObject{ } @property (nonatomic,assign) NSString *str1; @property (nonatomic,copy) NSString * str2; @property (nonatomic,retain) NSString * str3; @property (nonatomic) NSInteger age; @property (nonatomic,retain) NSString* name; -(MyClass2*) initCustom:(NSString*)name :(NSInteger)age; @end
MyClass2.m
#import "MyClass2.h" @implementation MyClass2 -(MyClass2*) initCustom:(NSString *)name :(NSInteger)age{ self = [super init]; if (self) { [self setName:name]; [self setAge:age]; } return self; } @end
Persion.h
#import "MyClass.h" @interface Persion : MyClass @property (nonatomic,copy) NSString* name; @end
Persion.m
#import "Persion.h" @implementation Persion @end
Student.h
#import <Foundation/Foundation.h> @interface Student : NSObject{ NSString* name; } -(void) myPrint; @end
Student.m
#import "Student.h" @implementation Student -(void) myPrint{ NSLog(@"myPrint"); } @end
StudentExt.h
#import "Student.h" @interface Student (hello){ } -(void) hello; @end
StudentExt.m
#import "StudentExt.h" @implementation Student (hello) -(void) hello{ NSLog(@"hello world"); } @end
CustomException.h
#import <Foundation/Foundation.h> @interface CustomException : NSException @end
CustomException.m
#import "CustomException.h" @implementation CustomException @end
Box.h
#import <Foundation/Foundation.h> @interface Box : NSObject @property (nonatomic) NSInteger num; -(void) setMyNum:(NSInteger)num; -(void) pushIn; -(void) pullOut; -(void) printNumber; @end
Box.m
#import "Box.h" #import "CustomException.h" #import "CustomException2.h" @implementation Box -(id) init{ self = [super init]; if (self) { [self setNum:0]; } return self; } -(void) setMyNum:(NSInteger)num{ self.num=num; if (self.num >= 10) { NSException* e=[CustomException2 exceptionWithName:@"customException222" reason:@"is larger than 10" userInfo:nil]; @throw e; }else if (self.num>=6) { NSException* e=[CustomException exceptionWithName:@"customException" reason:@"is larger than 6" userInfo:nil]; @throw e; }else if (self.num<0){ NSException* e=[NSException exceptionWithName:@"nsexception" reason:@"is small than 0" userInfo:nil]; @throw e; } } -(void) pushIn{ [self setMyNum:self.num+1]; } -(void) pullOut{ [self setMyNum:self.num-1]; } -(void) printNumber{ NSLog(@"%ld",(long)self.num); } @end
CustomException2.h
#import <Foundation/Foundation.h> @interface CustomException2 : NSException @end
CustomException2.m
#import "CustomException2.h" @implementation CustomException2 @end
附:创建测试工程
相关文章推荐
- Objective-C Class Dump
- swfobject.js 2.2简单使用方法
- object-c 之字符串的操作
- 如何动态修改DATAWINDOW OBJECT的数据源
- org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsav
- Objective-C中的instancetype
- 设计模式之美:Type Object(类型对象)
- ObjectMonitor,ObjectWaiter 实现wait(),notify()
- CocoaPods一个Objective-C第三方库的管理利器
- Kobject结构体分析
- java 序列化ObjectOutputStream 同一文件追加写对象问题的解决
- sql中的系统表sysobjects以及如何查看sql语句的执行时间
- 07-Objective-C特有语法:点语法
- Memory leak in IIS ADSOpenObject()
- 理解 objc_msgSend 的角色
- object-c学习:协议protocol
- Effective objective-C 理解消息forwarding
- 【原】Object 异常静态
- object c中的selector
- boost准模板库内存管理中pool和object_pool的使用