Я новичок в Objective-C. Я пытаюсь создать приложение погоды, где я обрабатывал данные с открытой карты погоды. Я сохранил проанализированные данные в массиве. Теперь вы хотите получить доступ к значению массива из другого класса, но получив нулевое значение.Как передать NSArray из класса NSObject классу UIViewController?
Может ли кто-нибудь мне помочь?
То, что я пробовал:
Вот мой NSObject
класса, где я хранение данных и пытаюсь отправить, что для просмотра контроллера:
- (void)getCurrentWeather:(NSString *)query
{
NSString *const BASE_URL_STRING = @"http://api.openweathermap.org/data/2.5/weather?q=";
NSString *const API_KEY = @"&APPID=APIKEYSTRING";
NSString *weatherURLText = [NSString stringWithFormat:@"%@%@%@",
BASE_URL_STRING, query,API_KEY];
NSURL *weatherURL = [NSURL URLWithString:weatherURLText];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:weatherURL];
[self performSelectorOnMainThread:@selector(fetchedDataSmile | :) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSString* cityName = [json objectForKey:@"name"];
int currentTempCelsius = (int)[[[json objectForKey:@"main"] objectForKey:@"temp"] intValue] - ZERO_CELSIUS_IN_KELVIN;
int maxTemp = (int)[[[json objectForKey:@"main"] objectForKey:@"temp_max"] intValue] - ZERO_CELSIUS_IN_KELVIN;
int minTemp = (int)[[[json objectForKey:@"main"] objectForKey:@"temp_min"] intValue] - ZERO_CELSIUS_IN_KELVIN;
NSString *weatherDescription = [[[json objectForKey:@"weather"] objectAtIndexBlush | :O ] objectForKey:@"description"];
weatherArray = [[NSMutableArray alloc] initWithObjects:cityName, weatherDescription,
[NSString stringWithFormat:@"%d", currentTempCelsius],
[NSString stringWithFormat:@"%d", maxTemp],
[NSString stringWithFormat:@"%d", minTemp],nil];
У меня есть NSObject.h файл как:
@interface WeatherData : NSObject
@property (nonatomic) NSString *weatherDescription;
@property (strong, nonatomic) NSString *currentTemp;
@property (nonatomic) int maxTempCelsius;
@property (nonatomic) int minTempCelsius;
@property (nonatomic, retain) NSMutableArray *weatherArray;
- (void)getCurrentWeather:(NSString *)query;
@end
На мой взгляд контроллера:
.h файл:
@property (nonatomic, retain) NSMutableArray *weatherResultArray;
.m файл:
-(void)searchButtonClicked:(UIButton*)sender
{
[self.view endEditing:YES];
WeatherData *weather = [[WeatherData alloc] init];
[weather getCurrentWeather:_textField.text];
self.weatherResultArray = weather.weatherArray;
//temperatureLabel.text = [NSString stringWithFormat:@"%d°",weather.currentTempCelsius];
}
Я просто хочу, чтобы показать результаты в UILabel.
С быстрым взглядом на ваш код Я считаю, что вы получаете NULL, потому что данные еще не вернулись с вашего HTTP-вызова, когда вы пытаетесь получить доступ к weather.weatherArray. Поэтому self.weatherResultArray имеет значение NULL. – jsondwyer
ваш тип возврата недействителен в функции выше, то как я могу получить массив! –
Легко передавать данные между контроллерами. Для этого вам нужно создать функцию делегата в NSObject.h. В этой функции вы создаете массив для данных о погоде. Все, теперь вам нужно добавить делегат в файл View Controller, и вы получите данные обратно при вызове делегата. – WasimSafdar