字符串的聲明
在OC中熬尺,用
NSString
類聲明的字符串時一個對象
- 用
@
創(chuàng)建字符串
NSString * str = @"hello string";
- 創(chuàng)建一個格式化的字符串
NSString * formatStr = [NSString stringWithFormat:@"name=%s,age=%d","zhangsan",10];
字符串輸出
NSLog(@"%@",str);
字符串的操作介紹
- 計算字符串的長度
NSUInteger len = [str length];
length
方法計算的是個數(shù)
結(jié)構(gòu)體作為對象屬性
- 聲明和實(shí)現(xiàn)
#import <Foundation/Foundation.h>
typedef struct{
int year;
int month;
int day;
} Date;
@interface User : NSObject
{
@public
NSString * _name;
Date _birthday;
}
- (void) say;
@end
@implementation User
- (void) say{
NSLog(@"name=%@,year=%i,month=%i,day=%i",_name,_birthday.year,_birthday.month,_birthday.day);
}
@end
- 調(diào)用
首先創(chuàng)建對象
User * user = [User new];
我們在對結(jié)構(gòu)體屬性進(jìn)行賦值時凑阶,要注意契邀,不能使用下面的方式
user->_birthday = {1999,1,1};
user->_birthday = {1999,1,1};
這種方式是錯誤的逛腿,因?yàn)橄到y(tǒng)在賦值時,無法判斷{1999,1,1}
是數(shù)組還是結(jié)構(gòu)體
對結(jié)構(gòu)體屬性進(jìn)行賦值荒辕,有三種方式
- 強(qiáng)制類型轉(zhuǎn)換
user->_birthday = (Date){1999,1,1};
- 先創(chuàng)建一個結(jié)構(gòu)體變量策泣,然后將這個變量賦值給該屬性
Date d ={1999,1,1};
user->_birthday = d;
- 對結(jié)構(gòu)體中的每一個變量分別進(jìn)行賦值
user->_birthday.year = 1999;
user->_birthday.month = 1;
user->_birthday.day = 1;
將對象作為方法的參數(shù)
@interface Gun : NSObject
- (void)shoot;
@end
@implementation Gun
- (void)shoot{
NSLog(@"shoot");
}
@end
@interface Soldider : NSObject
- (void)fire:(Gun *)gun;
@end
@implementation Soldider
- (void)fire:(Gun *)gun{
[gun shoot];
}
@end
//主函數(shù)
int main(int argc, const char * argv[]) {
Soldider *s = [Soldider new];
Gun *g = [Gun new];
[s fire:g];
return 0;
}