一、类的声明 //Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject {
/*成员变量声明在类的内部
*成员变量默认可访问属性为 @Protected
*OC中自定义的类或系统类对象都必须是一个指针
*/
NSString *_name;
NSString *_no;
int _age;
}
//+ 表示静态方法
+ (id)personWithName:(NSString *)name;
//- 表示动态方法
- (id)initWithName:(NSString *)name;
//get方法
- (NSString *)name;
//set方法,方法名是 setName:
- (void)setName:(NSString *)name;
- (NSString *)no;
- (void)setNo:(NSString *)no;
//方法名是 setName:andNo:
- (void)setName:(NSString *)name andNo:(NSString *)no;
- (int)age;
- (void)setAge:(int)age;
@end
#import "Person.h"
@implementation Person
+ (id)personWithName:(NSString *)name {
return [[[self alloc] initWithName:name] autorelease]; //通过静态方法创建的对象,应该自动释放
}
- (id)init {
return [self initWithName:nil];
}
- (id)initWithName:(NSString *)name {
if (self = [super init]) {
_name = [name copy];
}
return self;
}
- (void)dealloc {
[super dealloc];
NSLog(@"Person dealloc");
}
- (NSString *)name {
return _name;
}
- (void)setName:(NSString *)name {
_name = [name copy];
}
- (NSString *)no {
return _no;
}
- (void)setNo:(NSString *)no {
_no = [no copy];
}
- (void)setName:(NSString *)name andNo:(NSString *)no {
_name = [name copy];
_no = [no copy];
}
- (int)age {
return _age;
}
- (void)setAge:(int)age {
_age = age;
}
//重写父类的description方法
//当使用%@打印一个对象的时候调用
- (NSString *)description {
NSString *str = [NSString stringWithFormat:@"My name is %@, my identify card's number is %@, and I am %d years old.",
_name, _no, _age];
return str;
}
@end
三、类的使用 //main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [Person personWithName:@"dave"]; //调用静态方法创建对象
[person setNo:@"110001"];
[person setAge:25];
NSLog(@"My name is %@, my identify card's number is %@, and I am %d years old.",
[person name], [person no], [person age]);
Person *person2 = [[[Person alloc] init] autorelease]; //创建的时候指定autorelease,
//离开autoreleasepool的时候会自动释放
[person2 setName:@"john" andNo:@"110002"];
person2.age = 25; //OC点语法,等效于 [person2 setAge:25]
int age = person2.age; //OC点语法,等效于 [person age]
NSLog(@"My name is %@, my identify card's number is %@, and I am %d years old.",
person2.name, person2.no, age);
NSLog(@"%@", person2);
}
return 0;
}
本文探讨了Objective-C与Swift两种编程语言在iOS开发领域的应用与区别,包括其优势、特性和最佳实践,旨在帮助开发者选择合适的语言进行项目开发。

被折叠的 条评论
为什么被折叠?



