#import <Foundation/Foundation.h> @interface AddressCard : NSObject -(void)setName:(NSString *) theName; -(void)setEmail:(NSString *) theEmail; -(void)setfirstName:(NSString *)first lastName:(NSString *)last; //联系4 -(NSString *)firstName; -(NSString *)lastName; -(NSString *)name; -(NSString *)email; //系统生成访问器方法 @property (copy,nonatomic) NSString *name,*email,*firstName,*lastName; -(void)print; -(void)setName:(NSString *)theName andEmail:(NSString *) theEmail; @end
// // AddressCard.m // OC15数字字符串和集合 // // Created by Zoujie on 15/10/6. // Copyright ? 2015年 Zoujie. All rights reserved. // #import "AddressCard.h" @implementation AddressCard { NSString *name; NSString *email; } @synthesize name,email; -(void)setName:(NSString *)theName { // name = [NSString stringWithString:theName]; 老方法 if (name != theName) name = [NSString stringWithString:theName];//if语句测试发送到访问器方法的对象是否已经存在于实例变量中,如果传入的是同一个对象,就不需要再进行设置。 } -(void)setEmail:(NSString *)theEmail { if (email != theEmail) email = [NSString stringWithString:theEmail]; } //练习4 -(void)setfirstName:(NSString *)first lastName:(NSString *)last { if (_firstName != first){ _firstName = [NSString stringWithString:first]; } if (_lastName != last) _lastName = [NSString stringWithString:last]; } -(NSString *)name { return name; } -(NSString *)email { return email; } -(void)setName:(NSString *)theName andEmail:(NSString *)theEmail { self.name = theName; self.email = theEmail; } -(void)print { NSLog(@"================================="); NSLog(@"| |"); NSLog(@"|%-31s|",[name UTF8String]);//%-31s 表示用31个字符的字段宽度左对齐打印UTF8 C-字符串 修饰结果的作用 NSLog(@"|%-31s|",[email UTF8String]); NSLog(@"|%-31s|",[_lastName UTF8String]); NSLog(@"|%-31s|",[_firstName UTF8String]); NSLog(@"| |"); NSLog(@"| |"); NSLog(@"================================="); } -(NSComparisonResult)compareNames:(id)element { return [name compare:[element name]]; } @end
// // AddressBook.h // OC15数字字符串和集合 // // Created by Zoujie on 15/10/6. // Copyright ? 2015年 Zoujie. All rights reserved. // #import <Foundation/Foundation.h> #import "AddressCard.h" @interface AddressBook : NSObject @property (nonatomic,copy) NSString *bookName; @property (nonatomic,strong) NSMutableArray *book; -(instancetype) initWithName:(NSString *)name; -(void) addCard:(AddressCard *) theCard; -(NSInteger) entries;//获取卡片(AddressCard)数量 -(void)list; //通过名称查找地址卡片--假定精确匹配 -(AddressBook *) lookup:(NSString *) theName; //删除 -(void) removeCard:(AddressCard *)theCard; //排序 -(void)sort; @end
// // AddressBook.m // OC15数字字符串和集合 // // Created by Zoujie on 15/10/6. // Copyright ? 2015年 Zoujie. All rights reserved. // #import "AddressBook.h" @implementation AddressBook @synthesize bookName,book; //设置一个AddressBook的名称和一个空的AddressBook -(instancetype)initWithName:(NSString *)name { self = [super init]; if (self){ bookName = [NSString stringWithString:name]; book = [NSMutableArray array]; } return self; } -(instancetype)init { return [self initWithName:@"NoName"]; } -(void) addCard:(AddressCard *)theCard { [book addObject:theCard]; } -(NSInteger)entries { return [book count]; } -(void)list { NSLog(@"======== Contents of :%@ ========",bookName); for (AddressCard *theCard in book)//快速枚举 for( in) { NSLog(@"%-20s %-32s",[theCard.name UTF8String],[theCard.email UTF8String]); } NSLog(@"================================================="); } #pragma mark 查找 -(AddressCard *)lookup:(NSString *)theName { for (AddressCard *nextCard in book) { if ([nextCard.name caseInsensitiveCompare:theName]==NSOrderedSame) return nextCard; } return nil; // NSIndexSet NSUInteger result =[book indexOfObjectPassingTest:^BOOL(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { if ([[obj name] caseInsensitiveCompare:theName] == NSOrderedSame){ * stop = YES;//查找一个匹配,一个就足够了 return YES; } else return NO;//继续查找 }]; // 如果找到一个匹配,则查看它 if (result != NSNotFound)//只有一个元素 return book[result]; else return nil; } #pragma mark 删除 -(void)removeCard:(AddressCard *)theCard { [book removeObjectIdenticalTo:theCard];//方法会删除和参数所有相同的对象。但只有一个对象在数组中出现多次,才会出现这个问题 // [self isEqual:theCard]; } #pragma mark 排序 -(void)sort { // [book sortUsingSelector:@selector(compareNames:)];//需再AddressCard类中添加compareNames 方法 指定selector方法的比较器对数组排序 // 块方法直接排序,不用修改AddressCard类 [book sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { return [[obj1 name] compare:[obj2 name]]; }]; } @end
// // ViewController.h // OC15数字字符串和集合 // // Created by Zoujie on 15/10/5. // Copyright ? 2015年 Zoujie. All rights reserved. // #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> //使用Printint类别,将打印方法添加到NSSet @interface NSSet (Printing) -(void) print; @end @implementation NSSet (Printing) -(void) print { printf("{"); for (NSNumber *element in self) printf(" %li ",(long)[element integerValue]); printf("} \n"); } @end @interface NSDate (ElapsedDays) -(unsigned long) elapsedDays:(NSDate *) theDate; @end @implementation NSDate (ElapsedDays) -(unsigned long) elapsedDays:(NSDate *)theDate { NSDate *date = [NSDate date]; date = theDate; return date; } @end @interface ViewController : UIViewController @end
// // ViewController.m // OC15数字字符串和集合 // // Created by Zoujie on 15/10/5. // Copyright ? 2015年 Zoujie. All rights reserved. // #import "ViewController.h" #import "AddressCard.h" #import "AddressBook.h" //#import "NSSet(Printing)" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // [self studyNSNumber]; // 不可变字符串 // [self studyNSString]; // 可变字符串 // [self studyNSMutableNSString]; // 数组 // [self studyNSArray]; // 地址薄制作 // [self makeAddressCard]; // [self makeAddressCardTWO]; // AddressBook测试 // [self textAddressBook]; // 数组排序 // [self sortArray]; // NSValue类 // [self studyNSValue]; // NSDictionary // [self studyNSDictionary]; [self studyNSSet]; } #pragma mark NSNumber -(void)studyNSNumber { //常用基本数据类型int,float,double,long并不是对象 NSNumber *myNumber,*floatNumber,*intNumber; NSInteger myInt;//NSInterger不是一个对象,而是基本数据类型的typedef // integer型取值 intNumber = [NSNumber numberWithInt:10]; intNumber = @10;//字面量语法 myInt = [intNumber integerValue]; NSLog(@"%li",(long)myInt); // long型取值 myNumber = [NSNumber numberWithLong:0xabcdef]; NSLog(@"%lx",[myNumber longValue]); // char myNumber = [NSNumber numberWithChar:‘X‘]; myNumber = @‘X‘; NSLog(@"%c",[myNumber charValue]); // float floatNumber = [NSNumber numberWithFloat:10.00]; floatNumber = @10.00f; NSLog(@"%f",[floatNumber floatValue]); // double myNumber = [NSNumber numberWithDouble:12345e+15]; myNumber = @12345e+15; NSLog(@"%lg",[myNumber doubleValue]); //发生错误 NSLog(@"%li",(long)[myNumber integerValue]); // 验证两个Number是否相等 if ([intNumber isEqualToNumber:floatNumber]==YES) { NSLog(@"Number is Equal"); }else { NSLog(@"Numbers are not equal"); } if ([intNumber compare:myNumber]== NSOrderedAscending){ NSLog(@"First Number is less than second"); } /* // 注意 **************** NSNumber *yourNumber = [[NSNumber alloc]initWithInt:20]; [yourNumber initWithInt:10000];//直接修改会引起程序崩溃,所有数字对象都必须是新创建的; */ //NSDecimalNumber 提供一些四则运算方法 } #pragma mark 字符串 -(void)studyNSString { //格式字符 %@ 来显示NSString对象 NSString *str = @"Programming is fun"; NSLog(@"%@",str); // 不可变字符串的基本处理方式 NSString *str1 = @"This is String A"; NSString *str2 = @"This is String B"; NSString *res; NSComparisonResult compareResult; //计算字符串中得字符 NSLog(@"LengTh of Str1:%lu",[str1 length]); // 将一个字符串复制到另一个字符串 res = [NSString stringWithString:str1]; NSLog(@"copy:%@",res); // 将一个字符串复制到另一个字符串的末尾 str2 = [str1 stringByAppendingString:str2]; NSLog(@"%@",str2); // 验证两个字符串是否相等 if ([str1 isEqualToString:res]==YES) { NSLog(@"str1 = res"); } else { NSLog(@"str1 != res "); } // 验证一个字符串是否小于,等于或大于另一个字符串 compareResult = [str1 compare:str2]; if (compareResult == NSOrderedAscending) NSLog(@"str1 < str2"); else if (compareResult == NSOrderedSame) NSLog(@"str1 = str2"); else if (compareResult == NSOrderedDescending) NSLog(@"str1 > str2"); // 将字符串转换为大写 res = [str1 uppercaseString]; NSLog(@"Uppercase conversion:%s",[res UTF8String]); // 将字符串转换为小写 res = [str1 lowercaseString]; NSLog(@"Lowercase conversion:%@",res); NSLog(@"Orugunal string:%@",str1); NSRange subRange; // 从字符串中提取前3个字符 res = [str1 substringToIndex:3]; NSLog(@"Firest 3 chars of str1 %@",res); // 提取从索引5开始直到结尾的子字符串 res = [str1 substringFromIndex:5]; NSLog(@"Chars from index 5 of str1:%@",res); // 提取从索引5开始到索引13的子字符串(6个字符) res = [[str1 substringFromIndex:8] substringToIndex:6]; NSLog(@"Chars from index 8 through 13:%@",res); // 更简单的方法 res = [str1 substringWithRange:NSMakeRange(8, 6)]; NSLog(@"Chars from index 8 through 13:%@",res); // 从另一个字符串中查找一个字符串 subRange = [str1 rangeOfString:@"String A"]; NSLog(@"String is at index %lu, length is %lu",subRange.location,subRange.length); subRange = [str1 rangeOfString:@"String B"]; if (subRange.location == NSNotFound) NSLog(@"String not found"); else NSLog(@"String is at index %lu,length is %lu",subRange.location,subRange.length); // 常见的NSString方法 // NSString stringWithContentsOfFile:<#(nonnull NSString *)#> encoding:<#(NSStringEncoding)#> error:<#(NSError * _Nullable __autoreleasing * _Nullable)#> // 创建一个新字符串,并将其设置为path指定的文件的内容,使用字符编码enc,如果非零,则返回err中得错误 // [NSString stringWithContentsOfURL:<#(nonnull NSURL *)#> encoding:<#(NSStringEncoding)#> error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>] // 创建一个新字符串,并将其设置URL的内容,使用字符编码enc,如果非零,则返回err中得错误 // [NSString string];创建一个新的空字符串 // str1 compare:<#(nonnull NSString *)#> // 比较两个字符串 } #pragma mark 可变字符串 -(void)studyNSMutableNSString { NSString *str1 = @"This is String A"; NSString *search,*replace; NSMutableString *mstr; NSRange substr; //从不可变字符串创建可变字符串 mstr = [NSMutableString stringWithString:str1]; NSLog(@"%@",mstr); //插入字符 [mstr insertString:@"mutable" atIndex:7]; NSLog(@"%@",mstr); //插入末尾进行有效拼接 [mstr insertString:@" and string B" atIndex:[mstr length]]; NSLog(@"%@",mstr); //直接使用appendString [mstr appendString:@" and string C"]; NSLog(@"%@",mstr); //根据范围删除子字符串 [mstr deleteCharactersInRange:NSMakeRange(16, 13)]; NSLog(@"%@",mstr); //查找然后将其删除 substr = [mstr rangeOfString:@"string B and "]; if (substr.location != NSNotFound) { [mstr deleteCharactersInRange:substr]; NSLog(@"%@",mstr); } //直接设置为可变的字符串 [mstr setString:@"This is string A"]; NSLog(@"%@",mstr); //替换一些字符 [mstr replaceCharactersInRange:NSMakeRange(8, 8) withString:@"a mutable string"]; NSLog(@"%@",mstr); // 查找和替换 search = @"This is"; replace = @"An example of "; substr = [mstr rangeOfString:search]; if (substr.location != NSNotFound) { [mstr replaceCharactersInRange:substr withString:replace]; NSLog(@"%@",mstr); } // 查找和替换所有的匹配项 search = @"a"; replace = @"X"; substr = [mstr rangeOfString:search]; while (substr.location != NSNotFound) { [mstr replaceCharactersInRange:substr withString:replace]; substr = [mstr rangeOfString:search]; } NSLog(@"%@",mstr); // 如果需要把字符串分解为语言符号 ,可以查看NSScanner类 [NSMutableString stringWithCapacity:10];//创建一个初始包含10个字符的字符串 [[NSMutableString alloc]setString:mstr];//将字符串设置为mstr [[NSMutableString alloc] replaceOccurrencesOfString:search withString:replace options:24 range:NSMakeRange(0, [mstr length])];//根据选项options,在指定范围range中用replace替换所有的search. } #pragma mark NSArray -(void)studyNSArray { int i ; // 创建一个包含月份的数组 NSArray *monthName = [NSArray arrayWithObjects:@"Januay",@"February",@"March",@"April",@"May",@"June",@"July",@"August",@"September",@"October",@"Novermber",@"December", nil]; // 列出数组中得所有元素 NSLog(@"Month Name"); NSLog(@"=========="); for (i=0;i<12;i++) { NSLog(@"%i:%@",i+1,monthName[i]); } printf("\n"); NSArray *monthNames = @[@"Januay",@"February",@"March",@"April",@"May",@"June",@"July",@"August",@"September",@"October",@"Novermber",@"December"]; NSLog(@"Month Names"); NSLog(@"=========="); for (i=0;i<12;i++) { NSLog(@"%i:%@",i+1,monthNames[i]); } NSMutableArray *numbers = [NSMutableArray array]; for (i = 0;i<10;i++) { numbers[i][email protected](i); } // 遍历数组于显示其值 for (i=0;i<10;i++) { NSLog(@"%@",numbers[i]); } // 使用带有%@格式的NSlog显示 NSLog(@"==========USing a single NSLog"); NSLog(@"%@",numbers); } #pragma mark AddressCard 1 -(void)makeAddressCard { NSString *name = @"Zou JieMac"; NSString *email = @"[email protected]"; AddressCard *card1 = [[AddressCard alloc]init]; [card1 setName:name]; [card1 setEmail:email]; [card1 print]; } #pragma mark AddressCard 2 -(void)makeAddressCardTWO { NSString *aName = @"Zou JieMac"; NSString *aEmail = @"[email protected]"; NSString *bName = @"Chen wenTingSB"; NSString *bEmail = @"[email protected]"; AddressCard *cardZ = [[AddressCard alloc]init]; AddressCard *cardC = [[AddressCard alloc]init]; [cardZ setName:aName andEmail:aEmail]; [cardC setName:bName andEmail:bEmail]; [cardZ print]; [cardC print]; } #pragma mark AddressBook -(void)textAddressBook { NSString *aName = @"Zoujie Mac"; NSString *aEmail = @"[email protected]"; NSString *bName = @"Huangshuxian UI"; NSString *bEmail = @"[email protected]"; NSString *cName = @"Chenwenting SB"; NSString *cEmail = @"[email protected]"; AddressCard *card1 = [AddressCard new]; AddressCard *card2 = [AddressCard new]; AddressCard *card3 = [AddressCard new]; // AddressCard *card4 = [AddressCard new]; //创建一个新的地址薄 AddressBook *myBook = [[AddressBook alloc]initWithName:@"Love for Jie AddressBook"]; NSLog(@"Entries in address book after creation:%li",[myBook entries]); // 创建3个地址卡片 [card1 setName:aName andEmail:aEmail]; [card2 setName:bName andEmail:bEmail]; [card3 setName:cName andEmail:cEmail]; // 将地址卡片添加到地址薄 [myBook addCard:card1]; [myBook addCard:card2]; [myBook addCard:card3]; NSLog(@"Enter in address book after adding cards:%li",[myBook entries]); // 列出地址薄所有条目 [myBook list]; // 通过名字查找一个人 NSLog(@"lookup Huangshuxian"); AddressCard *myCard; myCard = [myBook lookup:@"Huangshuxian UI"]; if (myCard != nil) { [myCard print]; } else NSLog(@"Not found"); NSLog(@"lookup hanyifei"); myCard = [myBook lookup:@"hanyifei"]; if (myCard != nil) { [myCard print]; } else NSLog(@"Not found"); // 从电话薄中删除 myCard =[myBook lookup:@"Chenwenting SB"]; [myBook removeCard:myCard]; [myBook list]; } -(void)sortArray { NSString *aName = @"Zoujie Mac"; NSString *aEmail = @"[email protected]"; NSString *bName = @"Huangshuxian UI"; NSString *bEmail = @"[email protected]"; NSString *cName = @"Chenwenting SB"; NSString *cEmail = @"[email protected]"; AddressCard *card1 = [AddressCard new]; AddressCard *card2 = [AddressCard new]; AddressCard *card3 = [AddressCard new]; // AddressCard *card4 = [AddressCard new]; //创建一个新的地址薄 AddressBook *myBook = [[AddressBook alloc]initWithName:@"Love for Jie AddressBook"]; NSLog(@"Entries in address book after creation:%li",[myBook entries]); // 创建3个地址卡片 [card1 setName:aName andEmail:aEmail]; [card2 setName:bName andEmail:bEmail]; [card3 setName:cName andEmail:cEmail]; // 将地址卡片添加到地址薄 [myBook addCard:card1]; [myBook addCard:card2]; [myBook addCard:card3]; NSLog(@"Enter in address book after adding cards:%li",[myBook entries]); // 列出地址薄所有条目 [myBook list]; [myBook sort]; [myBook list]; // 常用的NSArray方法 NSArray *arrayText; [arrayText containsObject:myBook];//确定数组中是否包含对象 [arrayText count];//数组元素个数 [arrayText lastObject];//返回数组最后的对象 [arrayText objectAtIndex:1];//存储在元素1的对象 [arrayText makeObjectsPerformSelector:@selector(textArray)];//将selector指示的消息发送给数组中得每个元素 NSMutableArray *MutableArrayText; [MutableArrayText initWithCapacity:2];//指定初始的size给新的数组 [MutableArrayText addObject:myBook];//对象添加到数组的末尾 [MutableArrayText insertObject:card1 atIndex:3];//将对象插入到数组的序号3的位置 [MutableArrayText replaceObjectAtIndex:1 withObject:card2];//将序号1的对象用card2替换 [MutableArrayText removeObjectAtIndex:2];//删除数组序号为2的元素 } -(void)textArray { return; } #pragma mark NSValue类 -(void)studyNSValue { //将结构体转化为对象 CGPoint myPoint; CGSize mySize; CGRect myRect; NSValue *pointObjc; NSMutableArray *touchPoints = [NSMutableArray array]; myPoint.x = 100; myPoint.y = 200; mySize.height = 20; mySize.width = 40; myRect.origin = myPoint; myRect.size = mySize; pointObjc = [NSValue valueWithCGPoint:myPoint]; [touchPoints addObject:pointObjc]; pointObjc = [NSValue valueWithCGSize:mySize]; [touchPoints addObject:pointObjc]; pointObjc = [NSValue valueWithCGRect:myRect]; [touchPoints addObject:pointObjc]; NSLog(@"%@",touchPoints); // CGPoint youPoint; // NSLog(@"%@",[[touchPoints lastObject]rectValue]); } #pragma mark NSDictionary -(void)studyNSDictionary { NSMutableDictionary *glossary = [NSMutableDictionary dictionary]; // 存储三个条目在类别中 [glossary setObject:@"The Men like a girl" forKey:@"first_love"]; [glossary setObject:@"The Men must earn a lot of money" forKey:@"because_life"]; [glossary setObject:@"What the Men best like" forKey:@"i_know"]; NSLog(@"%@",[glossary objectForKey:@"first_love"]); NSLog(@"%@",[glossary objectForKey:@"because_life"]); NSLog(@"%@",[glossary objectForKey:@"i_know"]); // 新语法 dict[key] = object glossary[@"boy"] = @"I love you so much"; glossary[@"girl"] = @"you are my best love"; glossary[@"life"] = @"Family include men and women ,girl and boy,dog and cat"; NSLog(@"%@",glossary[@"boy"]); NSLog(@"%@",glossary[@"girl"]); NSLog(@"%@",glossary[@"life"]); // 打印字典中所有的键值对,和数组对象不一样,字典对象是无序的 for (NSString *key in glossary) { NSLog(@"%@:%@",key,[glossary objectForKey:key]); } // 常用的NSDictionary方法 // initWithObjectsAndKeys:@"obj1",@"key1",@"obj2",@"key2", nil 将新分配的词典初始化为键-对象{key1,obj1}{key2,obj2} // NSArray *sortKey = [glossary keysSortedByValueUsingSelector:<#(nonnull SEL)#>] 返回词典中得键数组,它根据selector指定的比较方法进行排序 } #pragma mark 集合NSSet -(void)studyNSSet { NSMutableSet *set1 = [NSMutableSet setWithObjects:@1,@3,@5,@10, nil]; NSSet *set2 = [NSSet setWithObjects:@-5,@100,@3,@5, nil]; NSSet *set3 = [NSSet setWithObjects:@12,@200,@3, nil]; NSLog(@"set1:"); [set1 print]; NSLog(@"set2:"); [set2 print]; // 相等性测试 if ([set1 isEqualToSet:set2]== YES) { NSLog(@"set1 equals set2"); } else { NSLog(@"set1 is not equal to set2"); } // 成员测试 if ([set1 containsObject:@10]==YES) NSLog(@"set1 contains 10"); else NSLog(@"set1 does not contain 10"); if ([set2 containsObject:@10]==YES) NSLog(@"set2 contains 10"); else NSLog(@"set2 does not contain 10"); // 在可变集合SET1中添加和移除对象 [set1 addObject:@4]; [set1 removeObject:@10]; NSLog(@"set1 after adding 4 and removing 10:"); [set1 print]; // 获得两个集合的交集 [set1 intersectSet:set2]; NSLog(@"set1 intersect set2:"); [set1 print]; // 两个集合的并集 [set1 unionSet:set3]; NSLog(@"set1 union set3"); [set1 print]; // 常用NSSet方法 [set2 anyObject];//返回集合中任一对象 [set2 containsObject:@10];//确定集合是否包含对象obj [set2 member:@10];//使用isEquak:方法确定集合是否包含OBJ // NSIndexSet 用于存储有序的索引到某种数据结构,比如数组 } @end
时间: 2024-10-07 05:26:03