从NSMutableArray中检索自定义对象

时间:2012-12-26 22:52:42

标签: objective-c

我的问题与this one非常相似,但是我没有从我的nil返回NSMutableArray而我已分配并初始化我的NSMutableArray。如何从索引处的name对象中检索Timeline值,例如3。 类似于以下内容:

NSLog(@"tlresults: %@",(Timeline *)[tlresults objectAtIndex:3].name);

并返回索引3的Timeline.name值。

Timeline.h

@interface Timeline : NSObject
{
    NSString *_name;
    NSInteger _up;
    NSInteger _down;
    NSInteger _timeofdatapoint;
}

@property (nonatomic,retain) NSString *name;
@property (nonatomic) NSInteger up;
@property (nonatomic) NSInteger down;
@property (nonatomic) NSInteger timeofdatapoint;

@end

Timeline.m

#import "Timeline.h"

@implementation Timeline

@synthesize name = _name;
@synthesize up = _up;
@synthesize down = _down;
@synthesize timeofdatapoint = _timeofdatapoint;

@end

向对象添加对象和测试检索的功能:

#import "Timeline.h"
...
NSMutableArray *tlresults = [[NSMutableArray alloc] init];

for (int i=0; i<10; i++) {

    Timeline *tlobj = [Timeline new];
    tlobj.name = username;
    tlobj.up = 2*i;
    tlobj.down = 5*i;
    tlobj.timeofdatapoint = 2300*i;

    [tlresults addObject:tlobj];
    [tlobj release];
}
NSLog(@"tlresults count: %d",[tlresults count]);
NSLog(@"marray tlresults: %@",(Timeline *)[tlresults objectAtIndex:3]);
...

输出:

tlresults count: 10
tlresults: Timeline: 0x7292eb0

2 个答案:

答案 0 :(得分:1)

编写强制转换以便您可以访问类实例的声明属性的正确方法是:

NSLog(@"tlresults: %@",((Timeline *)[tlresults objectAtIndex:3]).name);

NSLog(@"tlresults: %@",[(Timeline *)[tlresults objectAtIndex:3] name]);

或者,如果您需要访问很多属性:

Timeline *timelineAtIndex3 = [tlresults objectAtIndex:3];
NSLog(@"tlresults: %@", timelineAtIndex3.name);

答案 1 :(得分:0)

您需要覆盖描述方法,以便为将使用NSLog()打印的对象提供您自己的描述 由于您没有重写此方法,因此它使用了NSObject的方法,它只打印对象的内存地址。

例如:

- (NSString*) description
{
    return [NSString stringWithFormat: @"Name: %@ up: %li down: %li time of data point: %li",_name,_up,_down,_timeofdatapoint);
}

此外,按照惯例,属性名称不应为:

@property (nonatomic) NSInteger timeofdatapoint;

但是这个:

@property (nonatomic) NSInteger timeOfDataPoint;