OC 初始化方法和属性

建立一个Person类
Person.h

#import 
@interface Person : NSObject
{
  NSString *_name;
  NSString *_idCard;
  BOOL _isBoy;
  int _birthday;
}

- (id)initWithisBoy:(BOOL)isBoy withBirthday:(int)birthday;
- (void)setName:(NSString *)name;
- (void)setIdCard:(NSString *)idCard;

- (NSString *)name;
- (NSString *)idCard;
- (BOOL)isBoy;
- (int)birthday;

- (void)crying;

@end

Person.m

#import"Person.h"
@implementation Person

- (id)initWithIsBoy:(BOOL)isBoy withBirthday:(int)birthday
{  
  if(self = [super init])
    {
      //属性赋值
      _isBoy = isBoy;
      _birthday = birthday;
  
      NSLog(@"这是一个%@孩",isBoy?@"男":@"女");

      //调用方法
      [self crying];
    }
  return self;
}

/*
    self 指的是  类对象 本身
    super是  父类对象 本身
    self 用来调用  本类对象 的 实例变量和方法
    super 调用从 父类继承下来 的 方法
*/
/*________________________________________________*/
- (void)crying
{
  NSLog(@"哇哇大哭");
}

- (void)setName:(NSString *)name
{
    _name = name;
}

- (void)setIdCard:(NSString *)idCard
{
    _idCard = idCard;
}

/*____________________________________*/
- (NSString *)name
{
    return _name;
}

- (NSString *)idCard
{
    return _idCard;
}

- (BOOL)isBoy
{
    return _isBoy;
}

- (int)birthday
{
    return _birthday;
}

@end

main.m

#import 
#import "Person.h"

int main(int argc, const char * argv[])
{
  @autoreleasepool
  {  
    NSObject *objc = [NSObject alloc];
    objc = [objc init];

    Person *mouren = [[Person alloc]initWithIsBoy:NO wethBirthday:20160121];

    [mouren setName:@"某人"];
    [mouren setIdCard:@"123456789098"];

    NSLog(@"%@ %@ %@ %d",[mouren name],[mouren idCard],[mouren isBoy]?@"男":@"女",[mouren birthday]);

    [mouren crying];
  }
  return 0;
}

你可能感兴趣的:(OC 初始化方法和属性)