如何从自定义类中读取值

时间:2013-07-25 16:44:09

标签: objective-c

我有班级人员。

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject{
    NSString *name;
    NSString *screen_name;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *screen_name;

@end

Person.m

#import "Person.h"

@implementation Person

@synthesize text,screen_name;

@end

我有NSArray对象,带有值,例如text,screen_name等。

我做:

Person * person = object; ( object is NSArray)

我想获得价值,如下: person。名称,person。 screen_name

对象

{
        "screen_name" = "mika_alcala";
        "text" ="";
        "time_zone" = "Eastern Time (US & Canada)";
        "url" = "<null>";
        "utc_offset" = "-14400";
        "verified" = 0;
};

1 个答案:

答案 0 :(得分:1)

好的,首先您不需要定义ivars,也不需要使用XCode 4.5+(IIRC)进行合成。

所以看起来应该......

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *screen_name;

@end

Person.m

#import "Person.h"

@implementation Person

@end

对于实际问题,我不确定你在问什么。我要进一步询问......

编辑以显示如何从数组创建

首先关闭......

object :
{
        "screen_name" = "mika_alcala";
        "text" ="";
        "time_zone" = "Eastern Time (US & Canada)";
        "url" = "<null>";
        "utc_offset" = "-14400";
        "verified" = 0;
};

此对象实际上是NSDictionary而非NSArray

有两种方法可以做到这一点......

  1. 创建一个空白Person对象,然后设置字典中的值。

    Person *person = [[Person alloc] init];
    person.name = object[@"screen_name"];
    person.screen_name = object[@"screen_name"];
    
  2. Person对象添加自定义init方法。

  3. Person.h

    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject
    
    @property (nonatomic, retain) NSString *name;
    @property (nonatomic, retain) NSString *screen_name;
    
    - (id)initWithDictionary:(NSDictionary *)dictionary;
    
    @end
    

    Person.m

    #import "Person.h"
    
    @implementation Person
    
    - (id)initWithDictionary:(NSDictionary *)dictionary
    {
        self = [super init];
        if (self) {
            _name = dictionary[@"screen_name"];
            _screen_name = dictionary[@"screen_name"];
        }
        return self;
    }
    
    @end
    

    然后你就可以......

    Person *person = [[Person alloc] initWithDictionary:object];
    

    无论您采用哪种方法,您都可以获得person.nameperson.screen_name