【问题标题】:Accessing a variable in multiple methods以多种方法访问变量
【发布时间】:2013-04-03 07:56:22
【问题描述】:

还是有点新,我遇到了一些问题,希望有人能提供帮助。我正在尝试将来自我的服务器的 JSON 字符串加载到 iOS6 中的集合视图中 我可以使用从 viewDidLoad 方法调用的 fetchedData 方法提取数据,并且该部分工作正常。在 fetchedData 方法中,我将 JSON 数据分解并放在 NSDictionaries 和 NSArrays 中,然后可以将正确的数据转储到日志中查看。

问题是当我尝试在代码中的其他地方使用任何信息时,例如获取任何 hte 数组中的元素数量以用作填充集合视图的计数器。

可能是我累了,但我似乎无法理解这部分。许多主要变量的声明都在 fetchedData 方法中,我认为因为在那里声明了这可能是我在其他地方看不到它们的原因,所以我将变量的声明移到了接口部分并希望这样做变量 GLOBAL 和 fetchedData 方法继续正常工作,但没有其他地方。

当我在单元格定义区域中插入中断时,我可以在调试器窗口中看到变量显示为空。

我不确定您可能想查看代码的哪些部分,所以请告诉我,我可以发布它们,但也许有人可以举例说明如何以多种方法访问数组和字典项。

为了避免混淆并在这一点上公开我的大杂烩代码,这里是 .m 文件或至少其中的大部分文件请不要对我一直在尝试的任何我能想到的任何编码风格和我自己把它撕得很厉害,已经很晚了。

#import "ICBCollectionViewController.h"
#import "ICBCollectionViewCell.h"
#import "ICBDetailViewController.h"

@interface ICBCollectionViewController () {

NSDictionary* json;
NSDictionary* title;
NSDictionary* shortDescrip;
NSDictionary* longDescrip;
NSDictionary* price;
NSDictionary* path;
NSDictionary* sKU;
NSDictionary* audiotrack;
NSDictionary* audiotracksize;



NSArray* titles;
NSArray* shortDescription;
NSArray* longDescription;
NSArray* prices;
//    NSArray* paths;
NSArray* SKUs;
NSArray* audiotracks;
NSArray* audiotracksizes;
}
@end
/*
@interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;
-(NSData*)toJSON;
@end

@implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress
{
NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress] ];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}

-(NSData*)toJSON
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
@end
*/
@implementation ICBCollectionViewController
@synthesize paths;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: imobURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
});

// Do any additional setup after loading the view.
}

- (void)fetchedData:(NSData *)responseData {
NSError* error;
//parse out the json data
json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

titles = [json objectForKey:@"title"]; //2
shortDescription = [json objectForKey:@"shortD"];
longDescription =  [json objectForKey:@"longD"];
prices = [json objectForKey:@"price"];
self.paths = [json objectForKey:@"path"];
SKUs = [json objectForKey:@"SKU"];
audiotracks = [json objectForKey:@"audiotrack"];
audiotracksizes = [json objectForKey:@"audiotracksize"];

 NSLog(@"paths: %@", paths); //3
//  NSLog(@"shortDescrip: %@", shortDescription);

NSInteger t=7;
    // 1) Get the latest loan
    title = [titles objectAtIndex:t];
    shortDescrip = [shortDescription objectAtIndex:t];
    longDescrip = [longDescription objectAtIndex:t];
    price = [prices objectAtIndex:t];
    path = [paths objectAtIndex:t];
    sKU = [SKUs objectAtIndex:t];
    audiotrack = [audiotracks objectAtIndex:t];
    audiotracksize = [audiotracksizes objectAtIndex:t];

    //NSLog(title.count text);
    //NSLog(title.allValues);

    // 2) Get the data
    NSString* Title = [title objectForKey:@"title"];
    NSString* ShortDescrip = [shortDescrip objectForKey:@"shortD"];
    NSString* LongDescrip = [longDescrip objectForKey:@"longD"];
    NSNumber* Price = [price objectForKey:@"price"];
    NSString* Path = [path objectForKey:@"path"];
    NSString* SKU = [sKU objectForKey:@"SKU"];
    NSString* AudioTrack = [audiotrack objectForKey:@"audiotrack"];
    NSNumber* AudioTrackSize = [audiotracksize objectForKey:@"audiotracksize"];





    /*************************HERE THE DATA EXISTS*******************************/
    /******** Path = "XYXYXYXYXYXY" for example  ********************************/

    // 3) Set the label appropriately
    NSLog([NSString stringWithFormat:@"Here is some data: Title: %@ Path %@ SKU: %@ Price: %@ Track %@ Size %@",Title, Path, SKU, Price, LongDescrip, AudioTrackSize]);

}







- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//DetailSegue

if ([segue.identifier isEqualToString:@"DetailSegue"]) {
    ICBCollectionViewCell *cell = (ICBCollectionViewCell *)sender;
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    ICBDetailViewController *dvc = (ICBDetailViewController *)[segue destinationViewController];
    dvc.img = [UIImage imageNamed:@"MusicPlayerGraphic.png"];

}
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
NSLog(@"paths qty = %d",[paths count]);
return 20;
}

// The cell that is returned must be retrieved from a call to    -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier=@"Cell";
ICBCollectionViewCell *cell = (ICBCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

//    paths = [json objectForKey:@"path"];
NSDictionary* path = [paths objectAtIndex:indexPath.row];
NSString* Path = [path objectForKey:@"path"];
//    NSString* Path = [paths objectAtIndex:indexPath.row];
NSLog(@"%d",indexPath.row);



    /***********************HERE IT DOES NOT**************************/
    /******** Path = "" **********************************************/

NSLog(@"xxx");
NSLog(path);
NSLog(paths);
NSLog(Path);
NSLog(@"ZZZ");



Path=@"deepsleep";
NSLog(@"xxx");
NSLog(Path);
NSLog(@"ZZZ");





//    paths = [json objectForKey:@"path"];

//    NSString* Path = [path objectForKey:@"path"];

NSString *imagefile = [NSString stringWithFormat:@"https://imobilize.s3.amazonaws.com/glennharrold/data/%@/mid.png", Path];
NSLog(imagefile);
NSURL *url1=[NSURL URLWithString:imagefile];
dispatch_async(kBgQueue, ^{
    NSData *data1 = [NSData dataWithContentsOfURL:url1];
    cell.imageView.image =[[UIImage alloc]initWithData:data1];
});
return cell;
}


@end

【问题讨论】:

    标签: ios6 collectionview


    【解决方案1】:

    尝试分解 JSON 数据并在 appDelegate 中对其进行排序。如果您在 @property (nonatomic, strong) NSDictionary *myDict 等处声明公共变量,则可以通过导入您的 appDelegate 并使用以下代码来访问这些变量:

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSDictionary *newDict = appDelegate.myDict;
    

    否则,您可以将信息存储在singleton 或根视图控制器中。关键是将变量存储在不会被释放的类中。大多数情况下,为此目的使用 viewController 是一个坏主意——它们倾向于被导航离开,这会释放内存并摆脱你的变量。谷歌“模型-视图-控制器”了解更多信息。

    【讨论】:

    • 我所说的数据都在一个 .m 文件中,我将把该代码添加到我的问题中,它包含我提到的所有方法
    • 如果都在 .m 文件中声明,那么它就无法访问,因为属性不是公共的。
    • 这是否包括在顶部的同一个 .m 文件中使用它们我可以显示它们但在底部它们消失了我该如何更改?
    • 我从未尝试过使用单个 .m 文件进行多个实现。我建议使用 @property 在您的各个 .h 文件中声明变量,看看是否有帮助。
    【解决方案2】:

    我发现主要问题是 ViewDidLoad 方法,我使用后台活动从服务器获取 JSON 数据,并且由于该进程正在运行,前台也正在处理,因为其余代码是基于在后台进程完成时返回的值上,数据实际上为空,因此基于该单件的所有数据也为空,看起来好像不可用。一旦我让进程在前台运行,所有变量都开始具有值。

    感谢您对此的帮助

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 1970-01-01
      • 2018-11-15
      • 1970-01-01
      • 2014-09-14
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      相关资源
      最近更新 更多