gpt4 book ai didi

ios - 如何在单例 NSMutableArray 中添加对象

转载 作者:可可西里 更新时间:2023-11-01 17:14:39 26 4
gpt4 key购买 nike

我用来存放从服务器下载的数组数据。但是我不能将它们保存在单例数组中。

似乎无法访问该对象。

为什么 ulatitude、ulongitude、uaccuracy、uplacename 为 nil?...

在.h文件中

#import <Foundation/Foundation.h>
@interface LocationData : NSObject
{
NSMutableArray *ulatitude;
NSMutableArray *ulongitude;
NSMutableArray *uaccuracy;
NSMutableArray *uplacename;
}
@property (nonatomic, retain) NSMutableArray *ulatitude;
@property (nonatomic, retain) NSMutableArray *ulongitude;
@property (nonatomic, retain) NSMutableArray *uaccuracy;
@property (nonatomic, retain) NSMutableArray *uplacename;
+ (LocationData*) sharedStateInstance;
@end

在 .m 文件中

#import "LocationData.h"

@implementation LocationData

@synthesize uaccuracy;
@synthesize ulatitude;
@synthesize ulongitude;

+ (LocationData*) sharedStateInstance {
static LocationData *sharedStateInstance;

@synchronized(self) {
if(!sharedStateInstance) {
sharedStateInstance = [[LocationData alloc] init];
}
}
return sharedStateInstance;
}
@end

使用

[manager POST:urlStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
{

NSLog(@"%@",responseObject);

// json response array
if ([responseObject isKindOfClass:[NSArray class]]) {

NSArray *responseArray = responseObject;
NSDictionary *responseDict = [[NSDictionary alloc] init];

LocationData* sharedState = [LocationData sharedStateInstance];

for(NSUInteger i=0; i < responseArray.count; i++)
{
responseDict = [responseArray objectAtIndex:i];

double dlat = [[responseDict objectForKey:@"lat"] doubleValue];
double dlng = [[responseDict objectForKey:@"lng"] doubleValue];

[[sharedState ulatitude] addObject:[NSString stringWithFormat:@"%f",dlat]];
[[sharedState ulongitude] addObject:[NSString stringWithFormat:@"%f",dlng]];
[[sharedState uaccuracy] addObject:[responseDict objectForKey:@"rad"]];
[[sharedState uplacename] addObject:[responseDict objectForKey:@"place_name"]];
}

最佳答案

你总是需要初始化你的数组。在尝试向它们添加内容之前,您应该先做一些事情:

arrayName = [[NSMutableArray alloc] init];

否则你总是会出错,因为它们还没有被初始化。

在您的情况下,您应该像这样覆盖 LocationData init 函数:

- (instancetype)init {
self = [super init];
if (self) {
self.yourArrayName = [[NSMutableArray alloc] init];
// And so on....
}
return self;
}

关于ios - 如何在单例 NSMutableArray 中添加对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35406090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com