Cocoa是由两个不同的框架组成:Foundation Kit 和 Application Kit(AppKit)。AppKit包含了所有的用户接口对象和高级类。
1.范围
NSRange:用来表示相关事物的范围,定义于NSRange.h。通常是字符串里的字符范围或者数组(NSArray)里的元素范围。
1 typedef struct _NSRange {
2 NSUInteger location;
3 NSUInteger length;
4 } NSRange;
创建方法:
直接给字段赋值:
1 NSRange range;
2 range.location = 17;
3 range.length = 4;
或者,应用C语言的聚合结构赋值机制:
或者,适用Cocoa提供的函数NSMakeRange():
1 NSRange range = NSMakeRange ( 17 ,4 );
使用NSMakeRange函数的好处是你可以在任何能够使用函数的地方使用它。
2.几何数据类型
点:NSPoint //NSRange.h
1 typedef struct _NSPoint {
2 CGFloat x;
3 CGFloat y;
4 } NSPoint;
尺寸:NSSize //NSGeometry.h
1 typedef struct _NSSize {
2 CGFloat width;
3 CGFloat height;
4 } NSSize;
矩形:NSRect //NSGeometry.h
1 typedef struct _NSRect {
2 NSPoint origin;
3 NSSize size;
4 } NSRect;
创建函数:NSMakePoint() , NSMakeSize() , NSMakeRect()
将这些数据类型定义成C的struct而不是Objective-C的对象最根本的原本是因为性能。
3.字符串
1)创建格式字符串:NSSring的stringWithFormat:
1 NSString *myName;
2 myName = [NSString stringWithFormat:
3 @"My name is %@ , and I am %d yeas old.",
4 @"Elf Sundae",22];
2)NSString中的length方法返回字符串中的个数,可以处理国际字符串。如
1 NSLog(@"%d",[@"test测试" length]); //返回6
3)isEqualToString:字符串比较,返回BOOL
1 NSString *thing1 = @"hello,8";
2 NSString *thing2 = [NSString stringWithFormat:
3 @"hello,%d",7];
4 if ([thing1 isEqual: thing2]){
5 NSLog(@"Yes,they are the same.");
6 } else {
7 NSLog(@"NO,they are not the same.");
8 }
compare:逐个字符进行比较,
1 - (NSComparisonResult)compare:(NSString *)aString
compare:options: 带选项的比较字符串
- (NSComparisonResult)compare:(NSString *)aString
options:(NSStringCompareOptions)mask
返回一个NSComparisonResult的枚举值:
1 typedef enum _NSComparisonResult {
2 NSOrderedAscending = -1, // <
3 NSOrderedSame, // =
4 NSOrderedDescending // >
5 } NSComparisonResult;
“==”运算符只判断两个字符串的指针数值,而不是它们所指的对象,以下例子请区别:
NSString *thing1 = @"hello,8";
NSString *thing2 = [NSString stringWithFormat:
@"hello,%d",8];
if ([thing1 isEqual: thing2]){
NSLog(@"Yes,they are the same.");
} else {
NSLog(@"NO,they are not the same.");
}
if (thing1 == thing2){
NSLog(@"thing1 == thing2");
} else{
NSLog(@"thing1 != thing2");
}
输出:
2010-10-21 14:47:14.282 FoundationKit1[1965:a0f] Yes,they are the same.
2010-10-21 14:47:14.282 FoundationKit1[1965:a0f] thing1 != thing2
字符串匹配查询
// 检查字符串是否以另一个字符串开头
- (BOOL)hasPrefix:(NSString *)aString
// 检查字符串是否以另一个字符结尾
- (BOOL)hasSuffix:(NSString *)aString
例如:
BOOL b = [@"test" hasSuffix: @"st"];
// 查询是否包含某字符串,返回匹配部分在哪里以及能够匹配的字符个数(NSRange类型)
- (NSRange)rangeOfString:(NSString *)aString
Returns {NSNotFound, 0} if aString is not found or is empty (@"").
// rangeOfString:options:
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
4)可变性
NSString是不可变的,一旦NSString被创建,就不能改变它。可以用它来生成新的字符串,查找字符串或将它与其他字符串比较,但是不能以删除字符或者添加字符的方式来改变它。
如果想改变字符串,请使用NSString的子类NSMutableString。
NSString类似Java中的String,NSMutableString类似与Java中的StringBuffer。
创建NSMutableString:stringWithCapacity:
+ (id) stringWithCapacity: (unsigned) capacity;
这个capacity(容量)只是给NSMutableString的一个建议,字符串的大小并不限制与所提供的capacity,这个capacity只是个最优值。
NSMutableString *string;
string = [NSMutableString stringWithCapacity:42];
一旦有了一个可变字符串,就可以对它执行各种操作了。
附加字符串:appendString: 或 appedFormat:
由于NSMutableString是NSString的之类,所以在任何使用NSString的地方都可以用NSMutableString代替,与实例方法一样,继承同样对类方法(类似其他语言中的静态方法,定义前缀为加号 + )也适用。
Example:
OBJECTIVE-C CODE :NSMutableString
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //NSMutableString NSMutableString *string; // 创建 string = [NSMutableString stringWithCapacity:40]; // append [string appendString: @"Hello,"]; [string appendFormat: @"World! %d",1024]; NSLog(@"%@",string); // Hello,World! 1024 // delete characters NSRange worldRange; worldRange = [string rangeOfString: @"World"]; [string deleteCharactersInRange:worldRange]; NSLog(@"%@",string); // Hello,! 1024 // 由于NSMutableString是继承自NSString, // 所以NSMutableString可以使用NSString的方法 NSMutableString *str; str = [NSMutableString stringWithFormat: @"My age is %d",22]; NSLog(@"%@",str); [pool drain]; return 0; }
4.集合 集合类:NSArray 、NSDictionary 1)NSArray NSArray是Cocoa的一个类,用来存储对象的有序列表,可以在NSArray中放入任意类型的对象。 NSArray中只能存储Objective-C的对象,而不能存储C语言中的基本数据类型,如int,float,enum,struct,或者NSArray中的随机指针。同时,也不能在NSArray中存储nil(对象的零值或NULL值)。 1 #import <Foundation/Foundation.h> 2 3 4 5 int main (int argc, const char * argv[]) { 6 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 7 8 // 创建数组 arrayWithObjects: 9 NSArray *array; 10 array = [NSArray arrayWithObjects: 11 @"one", @"two", @"three", nil]; //列表结尾添加nil表示列表结束 12 13 // 获取对象个数 count: 14 NSLog(@" the count of array is: %d", 15 [array count]); 16 17 // 获取特定索引处的对象 objectAtIndex: 18 int i; 19 for (i = 0 ; i < [array count]; i++) 20 { 21 NSLog(@"index %d has %@", 22 i,[array objectAtIndex:i]); 23 } 24 25 // 将字符串切分成数组 componentsSeparatedByString: 26 NSString *str = @"oop : ack : elf : com : cn : net"; 27 NSArray *arr = [str componentsSeparatedByString:@" : "]; 28 NSLog(@"str is : %@",str); 29 NSLog(@"arr is :"); 30 for (NSString *s in arr) 31 { 32 NSLog(@"\"%@\"",s); 33 } 34 // 合并数组并创建字符串 componentsJoinedByString: 35 NSLog(@"合并数组到NSArray."); 36 str = [arr componentsJoinedByString:@" , "]; 37 NSLog(@"str is : %@",str); 38 NSLog(@"arr is :"); 39 for (NSString *s in arr) 40 { 41 NSLog(@"\"%@\"",s); 42 } 43 44 45 [pool drain]; 46 return 0; 47 } 48 49 50
2)可变数组: 与NSString一样,一旦创建NSArray它就固定下来了,不能添加或删除其中的任何元素。当然,包含在数组中的对象是可以改变的,当数组对象本身一直都不会改变。 可变数组可以使用NSMutableArray Example:
1 // 2 // MyClass.h 3 // FoundationKit4 4 // 5 // Created by Elf Sundae on 10/22/10. 6 // Copyright 2010 Control-Strength. All rights reserved. 7 // 8 9 #import <Cocoa/Cocoa.h> 10 11 12 @interface MyClass : NSObject 13 { 14 NSString *firstName; 15 NSString *lastName; 16 } 17 18 19 - (void) setFirstName:(NSString *)m_firstName; 20 - (NSString *) firstName; 21 22 - (void) setLastName: (NSString *) m_lastName; 23 - (NSString *) lastName; 24 25 - (NSString *) fullName; 26 27 @end
1 // 2 // MyClass.m 3 // FoundationKit4 4 // 5 // Created by Elf Sundae on 10/22/10. 6 // Copyright 2010 Control-Strength. All rights reserved. 7 // 8 9 #import "MyClass.h" 10 11 12 @implementation MyClass 13 14 - (void) setFirstName:(NSString *)m_firstName{ 15 16 firstName = m_firstName; 17 } 18 - (NSString *) firstName{ 19 return firstName; 20 } 21 22 - (void) setLastName: (NSString *) m_lastName{ 23 lastName = m_lastName; 24 } 25 - (NSString *) lastName{ 26 return lastName; 27 } 28 29 30 - (NSString *) fullName 31 { 32 if (firstName == nil || lastName == nil) { 33 return @"No Name found."; 34 } else { 35 return [NSString stringWithFormat:@"%@ %@", 36 firstName,lastName]; 37 } 38 39 } 40 @end
1 // 2 // FoundationKit4.m 3 // 4 5 #import <Foundation/Foundation.h> 6 #import "MyClass.h" 7 8 int main (int argc, const char * argv[]) { 9 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 10 11 // 创建可变数组 12 NSMutableArray *array; 13 array = [NSMutableArray arrayWithCapacity: 20]; 14 // 添加对象: addObject 15 int i; 16 for (i = 0; i < 4; i++) 17 { 18 MyClass *myClass = [MyClass new]; 19 [array addObject:myClass]; 20 } 21 [[array objectAtIndex:0] setFirstName:@"Elf"]; 22 [[array objectAtIndex:0] setLastName:@"Sundae"]; 23 24 [[array objectAtIndex:3] setFirstName:@"Joe"]; 25 [[array objectAtIndex:3] setLastName:@"Gates"]; 26 27 28 for (MyClass *my in array) 29 { 30 NSLog(@"%@",[my fullName]); 31 } 32 33 // 删除对象:removeObjectAtIndex: 34 NSLog(@"删除第二个对象后:"); 35 [array removeObjectAtIndex:1]; 36 37 for (MyClass *my in array) 38 { 39 NSLog(@"%@",[my fullName]); 40 } 41 42 [pool drain]; 43 return 0; 44 } 45 46
3)枚举 (NSEnumerator) 遍历数组每个索引处的对象,你可以编写一个0到[array count]的循环,而NSEnumerator用来描述这种集合迭代运算的方式。 通过objectEnumerator向数组请求枚举器,如果想从后向前浏览集合,可使用reverseObjectEnumerator方法。在获得枚举器后,可以开始一个while循环,每次循环都向这个枚举器请求它的下一个对象:nextObject。nextObject返回nil值时,循环结束。示例如下:
1 // NSEnumerator示例 2 NSEnumerator *enumerator; 3 enumerator = [array objectEnumerator]; 4 id thing; 5 while (thing = [enumerator nextObject]) { 6 NSLog(@"I found %@",thing); 7 }
对于可变数组进行枚举操作时,主要不要添加或删除数组中的对象。 4)快速枚举 Objective-C2.0支持快速枚举:如
1 for (NSString *string in array) 2 { 3 NSLog(@" I found %@",string); 4 } 5 6
这个循环将会遍历数组中的每个元素,并且用变量string存储每个数组值。它比枚举器语法更加简洁快捷。 5)字典:NSDictionary 字典就是关键字及其定义(描述)的集合。Cocoa中的实现字典的集合NSDictionary在给定的关键字(通常是一个NSString)下存储一个数值(可以是任何类型的对象)。然后你就可以用这个关键字来查找相应的数值。 不同于数组,字典(也被称为散列表或关联数组)使用的是键查询的优化存储方式。它可以立即找出要查询的数据,而不需要遍历整个数组进行查找。 可使用dictionaryWithObjectsAndKeys来创建字典 查询字典的值:objectForKey NSMutableDictionary的dictionary方法可以创建一个可变字典,也可以使用dictionaryWithCapaticy:。 使用 setObject:forkey: 方法添加字典元素,如果关键字已存在,则用新植替换旧值。 类似的,NSMutableDictionary类允许随意添加或删除字典元素。 添加元素:setObject:forkey: 删除元素:removeObjectForKey: Example: 1 // 2 // MyClass.h 3 // FoundationKit4 4 // 5 // Created by Elf Sundae on 10/22/10. 6 // Copyright 2010 Control-Strength. All rights reserved. 7 // 8 9 #import <Cocoa/Cocoa.h> 10 11 12 @interface MyClass : NSObject 13 { 14 NSString *firstName; 15 NSString *lastName; 16 } 17 18 19 - (void) setFirstName:(NSString *)m_firstName; 20 - (NSString *) firstName; 21 22 - (void) setLastName: (NSString *) m_lastName; 23 - (NSString *) lastName; 24 25 26 @end
1 // 2 // MyClass.m 3 // FoundationKit4 4 // 5 // Created by Elf Sundae on 10/22/10. 6 // Copyright 2010 Control-Strength. All rights reserved. 7 // 8 9 #import "MyClass.h" 10 11 12 @implementation MyClass 13 14 - (void) setFirstName:(NSString *)m_firstName{ 15 16 firstName = m_firstName; 17 } 18 - (NSString *) firstName{ 19 return firstName; 20 } 21 22 - (void) setLastName: (NSString *) m_lastName{ 23 lastName = m_lastName; 24 } 25 - (NSString *) lastName{ 26 return lastName; 27 } 28 29 30 - (NSString *) description 31 { 32 if (firstName == nil || lastName == nil) { 33 return @"No Name found."; 34 } else { 35 return [NSString stringWithFormat:@"%@ %@", 36 firstName,lastName]; 37 } 38 39 } 40 41 @end
1 /* 2 * 示例字典(NSDictionary,NSMutableDictionary)操作 3 * 4 * Elf Sundae 10/22/2010 5 */ 6 7 #import <Foundation/Foundation.h> 8 #import "MyClass.h" 9 10 int main (int argc, const char * argv[]) { 11 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 12 13 // 创建字典:dictionaryWithObjectsAndKeys: 14 MyClass *my1 = [MyClass new]; 15 MyClass *my2 = [MyClass new]; 16 MyClass *my3 = [MyClass new]; 17 MyClass *my4 = [MyClass new]; 18 19 NSDictionary *myClassDict; 20 myClassDict = [NSDictionary dictionaryWithObjectsAndKeys: 21 my1, @"my1", 22 my2, @"my2", 23 my3, @"my3", 24 my4, @"my4", nil]; 25 // 获取值 objectForKey 26 MyClass *sub = [myClassDict objectForKey: @"my3"]; 27 if (sub == nil) { 28 exit(1); 29 } 30 [sub setFirstName:@"Elf"]; 31 [sub setLastName:@"Sundae"]; 32 33 NSLog(@"修改数据: %@",sub); 34 35 // 遍历字典 36 NSLog(@"***遍历字典myClassDict如下:"); 37 for (id key in myClassDict) 38 { 39 NSLog(@"key: %@ ,value: %@",key,[myClassDict objectForKey:key]); 40 } 41 NSLog(@"***遍历字典myClassDict结束。"); 42 43 // MARK: *** 添加新元素 *** 44 // NSDictionary无法添加或删除元素,可以使用NSMutableDictionary. 45 NSMutableDictionary *myNewDict = [NSMutableDictionary dictionary]; 46 // 将原有字典添加到新字典的一对元素 47 //[myNewDict setObject:myClassDic forKey:@"旧的不可变字典myClassDic"]; 48 49 // 遍历添加已有数据(原字典) 50 for (id key in myClassDict) 51 { 52 [myNewDict setObject: [myClassDict objectForKey:key] 53 forKey:key]; 54 } 55 56 NSString *newkey = @"newKey"; 57 NSString *newValue = @"This is a new Value."; 58 [myNewDict setObject:newValue forKey:newkey]; 59 60 // 遍历myNewDict 61 NSLog(@"***遍历字典myNewDict如下:"); 62 for (id key in myNewDict) 63 { 64 NSLog(@"key: %@ ,value: %@",key,[myNewDict objectForKey:key]); 65 } 66 NSLog(@"***遍历字典myNewDict结束。"); 67 68 // 删除元素 69 [myNewDict removeObjectForKey: @"newKey"]; 70 71 // 遍历myNewDict 72 NSLog(@"***遍历字典myNewDict如下:"); 73 for (id key in myNewDict) 74 { 75 NSLog(@"key: %@ ,value: %@",key,[myNewDict objectForKey:key]); 76 } 77 NSLog(@"***遍历字典myNewDict结束。"); 78 79 [pool drain]; 80 return 0; 81 }
// 输出结果(省略日期 时间等信息) 修改数据: Elf Sundae ***遍历字典myClassDict如下: key: my3 ,value: Elf Sundae key: my4 ,value: No Name found. key: my1 ,value: No Name found. key: my2 ,value: No Name found. ***遍历字典myClassDict结束。 ***遍历字典myNewDict如下: key: newKey ,value: This is a new Value. key: my3 ,value: Elf Sundae key: my4 ,value: No Name found. key: my1 ,value: No Name found. key: my2 ,value: No Name found. ***遍历字典myNewDict结束。 ***遍历字典myNewDict如下: key: my3 ,value: Elf Sundae key: my4 ,value: No Name found. key: my1 ,value: No Name found. key: my2 ,value: No Name found. ***遍历字典myNewDict结束。 6)类簇 在Cocoa中,许多类实际上是以类簇的方式实现的,即它们是一群隐藏在通用接口之下的与实现相关的类。例如创建NSString对象时,实际上获得的可能是NSLiteralString、NSCFString、NSSimpleCString、NSBallOfString或者其他未写入文档的与实现相关的对象。 所以,请不要尝试去创建NSString、NSArray或NSDictionary的子类。 在实际编程中,需要需要,可以通过将NSString或NSArray复合到你的某个类中或者使用类别(以后会介绍到)来解决这种编程问题,而不用创建子类。
|