Dark Matter
Dark Matter

Reputation: 3698

how to read values from custom class

I have class Person.

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

I have NSArray object, with values, such as text, screen_name and etc.

I do:

Person * person = object; ( object is NSArray)

I would like get values, like this: person.name, person.screen_name

object :

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

Upvotes: 0

Views: 47

Answers (1)

Fogmeister
Fogmeister

Reputation: 77641

OK, first you don't need to define the ivars and you don't need the synthesize with XCode 4.5+ (IIRC).

So it should look like...

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

For the actual question I'm not sure what you're asking. I'll have to ask further...

EDIT to show how to create from array

First off...

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

This object is actually an NSDictionary not and NSArray.

There are two ways of doing this...

  1. Create a blank Person object and then set the values from the dictionary.

    Person *person = [[Person alloc] init];
    person.name = object[@"screen_name"];
    person.screen_name = object[@"screen_name"];
    
  2. Add a custom init method to the Person object.

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

Then you can just do...

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

Whichever method you follow you will then be able to get hold of person.name and person.screen_name.

Upvotes: 1

Related Questions