Все еще немного новое, и у меня возникают некоторые проблемы. Я надеялся, что с кем-то это поможет. Я пытаюсь загрузить строку JSON, исходящую с моего сервера, в viewview в iOS6 Я могу вытащить данные с помощью метода fetchedData, вызванного методом viewDidLoad, и эта часть работает нормально. В методе 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 *[email protected]"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");
[email protected]"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
данные, которые я имею в виду все в одном файле .m я добавлю этот код на мой вопрос он содержит все методы, которые я уже –
Если это все заявленные в. m, то он не будет доступен, поскольку свойства не являются общедоступными. – AMayes
Включает ли это их использование в том же файле .m в верхней части, что я могу показать их, но внизу они исчезли, как я могу это изменить? –