如何在Objective C中从Object 1转换为Object 2

时间:2014-05-03 14:31:10

标签: objective-c

如何将Object转换为Person以访问其属性,如

((Person)self.dataObject).firstName;

除了clang不接受这种语法:

DataViewController.h

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.dataLabel.text = ((Person)self.dataObject).firstName;
}

DataViewController.h

#import <UIKit/UIKit.h>

@interface DataViewController : UIViewController
@property (strong, nonatomic) IBOutlet UILabel *dataLabel;
@property (strong, nonatomic) id dataObject;

@end

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property NSString* firstName;
@property NSString* lastName;

@end

1 个答案:

答案 0 :(得分:3)

你不是把它作为指向对象的指针。相反,你应该按如下方式进行投射:

((Person *)self.dataObject).firstName;