今天开始学习oc,mark一下,到时候看自己多久能学会。
如果有错误或者需要完善的希望好心人能够帮帮忙解释一下
HelloWorld.h
#import<Foundation/Foundation.h>
@interface HelloWorld : NSObject{
@private// 属性声明
NSString *_des;
NSString *_name;
NSString *_id;
}
- (id) initWithStrAndName : (NSString*) str withName : (NSString*) name withID : (NSString *)idStr;// id为指向对象的指针
- (void) printName;
- (void) printDes;
+ (void) thisIsStaticMethod;
@end
HelloWorld.m
</pre><p></p><pre name="code" class="objc">#import "HelloWorld.h"
@implementation HelloWorld
- (id) initWithStrAndName:(NSString *)des withName : (NSString *)name withID: (NSString *)idStr{//以init开头的为构造方法
self = [super init];//首先调用super的init方法
if (self) {
self->_des = des;
self->_name = name;
self->_id = idStr;
}
return self;
}
- (void) printName {
[self printID];//调用类的私有方法
NSLog(@"%@",self->_name);
}
- (void) printDes {
NSLog(@"%@",self->_des);
}
- (void) printID {//该方法未在.h文件中声明,为私有方法,HelloWord的实例不可调用
NSLog(@"%@", self->_id);
}
+ (void) thisIsStaticMethod{// +开头的为静态方法
NSLog(@"this is a static method");
}
@end
main.m
#import <Foundation/Foundation.h>
#import "HelloWorld.h"
BOOL areIntsDifferent(int thing1, int thing2){
if (thing1 == thing2) {
return NO;
}
return YES;
}
NSString *boolString(BOOL yesNo){
if (YES == yesNo) {
return @"YES";
}
return @"NO";
}
int main(int argc, const char * argv[]) {
BOOL isDifferent = areIntsDifferent(100, 50);
NSLog(@"%d and %d are different? %@", 100, 50, boolString(isDifferent));
HelloWorld * hello = [[HelloWorld alloc]initWithStrAndName:@"description:hello world" withName : @"my name is Lily" withID: @"my id is 100"];
[hello printDes];
[hello printName];
[HelloWorld thisIsStaticMethod];
return 0;
}
方法声明方式:
-(returnType)method
-(returnType)method:(dataType)param1
-(returnType)method:(dataType)param1 withParam:(dataType)param2