Adding objects to array NSXMlParser no data - xcode

I'm trying to make a XML-parser that saves data from YR.no-API. The parser should add data to these two datastructures. My problem is when i try to add a WeatherTimeData object to my array in WeatherData, it seems like the objects doesnt get added, the following count always give me zero
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementname isEqualToString:#"time"])
{
[self.weatherdata.timedata addObject:currentWeatherTimeData];
NSLog(#"amount of objects in timedata-array %d", [[self.weatherdata timedata] count]);
}
These are my two data-structures, i alloc weatherData in the following method
-(id) loadXMLByURL:(NSString *)urlString
{
_weatherdata = [[WeatherData alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}
Do i have to alloc the array inside of the weatherdata object?
WeatherData.h
#interface WeatherData : NSObject
#property (strong, nonatomic)NSString *town;
#property (strong, nonatomic)NSString *country;
#property (strong, nonatomic)NSMutableArray *timedata;
#end
WeatherData.m
#implementation WeatherData
#synthesize town = _town;
#synthesize country = _country;
#synthesize timedata = _timedata;
#end
WeatherTimeData.h
#interface WeatherTimeData : NSObject
#property (strong, nonatomic)NSDate *startTime;
#property (strong, nonatomic)NSDate *endTime;
#property (strong, nonatomic)NSString *iconSymbol;
#property (strong, nonatomic)NSString *windDirection;
#property (strong, nonatomic)NSString *windSpeed;
#property (strong, nonatomic)NSString *temprature;
#property (strong, nonatomic)NSString *preassure;
#end
WeatherTimeData.m
#implementation WeatherTimeData
#synthesize startTime = _startTime;
#synthesize endTime = _endTime;
#synthesize iconSymbol = _iconSymbol;
#synthesize windDirection = _windDirection;
#synthesize windSpeed = _windSPeed;
#synthesize temprature = _temprature;
#synthesize preassure = _preassure;
#end

This type of problem is classically because the object hasn't been allocated, and given Objective-C allows messages to be sent to nil the programmer doesn't notice.
I think it would be nice to be able to provide a runtime environment variable where such events are logged to stdout...
I would suspect that [WeatherTimeData init] isn't creating timedata and that's because you haven't provided an implementation for it; just using #sythensize isn't enough to create the objects.

Related

Compilation fails due to prototype cell

I have a TableViewController subclass with one prototype cell designed in storyboard. Then I am passing the references to the class header etc and for some reason it fails to compile it. But the connections seem fine. I provide you the code and pictures of the build errors and the storyboard. I am using Xcode 4.3.3. Any help is really appreciated.
favTable.h
#import <UIKit/UIKit.h>
#interface favTable : UITableViewController <NSFetchedResultsControllerDelegate>
{
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;
NSArray *favArr;
NSMutableArray *favName;
NSMutableArray *favScore;
}
#property (nonatomic, retain) NSArray *favArr;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, strong) NSMutableArray *favName;
#property (nonatomic, strong) NSMutableArray *favScore;
#property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
#property (strong, nonatomic) IBOutlet UITableViewCell *celldes;
#property (strong, nonatomic) IBOutlet UIImageView *cellimage;
#property (strong, nonatomic) IBOutlet UILabel *cellname;
#property (strong, nonatomic) IBOutlet UILabel *cellmanu;
#property (strong, nonatomic) IBOutlet UILabel *cellscore;
#end
favTable.m
#import "favTable.h"
#import "ecoAppDelegate.h"
#interface favTable ()
#end
#implementation favTable
#synthesize favArr;
#synthesize managedObjectContext;
#synthesize fetchedResultsController;
#synthesize favName;
#synthesize favScore;
#synthesize celldes;
#synthesize cellimage;
#synthesize cellname;
#synthesize cellmanu;
#synthesize cellscore;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Favorites";
self.navigationController.navigationBar.translucent = NO;
// passing the array of addedtofavorites to the total one with all favorites
self.managedObjectContext = ((ecoAppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"FavoritesInfo" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
fetchRequest.resultType = NSDictionaryResultType;
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:#"name", nil]];
NSError *error=nil;
self.favArr=[[self.managedObjectContext executeFetchRequest:fetchRequest error:&error]mutableCopy];
if (error!=nil) {
NSLog(#" fetchError=%#,details=%#",error,error.userInfo);
}
self.favName = [[self.favArr valueForKey:#"name"] mutableCopy];
self.favScore = [[self.favArr valueForKey:#"score"] mutableCopy];
}
- (void)viewDidUnload
{
[self setCelldes:nil];
[self setCellimage:nil];
[self setCellname:nil];
[self setCellmanu:nil];
[self setCellscore:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return [favName count];;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
// Configure the cell...
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cellname.text = #"Test";
return cell;
}
#end
I moved manually the IB outlets into a separate custom cell class and then linked the references to the storyboard (maybe this is fixed in newer versions)
Then applied that cell style in the prototype cell and simply changed the content of the UI items of my cell using the identifier (no tag was needed)

100% memory leak in gcd block

I have an arc-enabled project which has PersonModel class:
// .h
#interface PersonModel : NSObject
#property (strong, nonatomic) NSString *photoUrl;
#property (strong, nonatomic) UIImage *photo;
#property (strong, nonatomic) NSString *fio;
#end
// .m
#implementation PersonModel
#synthesize photoUrl;
#synthesize photo = _photo;
#synthesize fio;
- (UIImage *)photo
{
if (_photo == nil && self.photoUrl) {
_photo = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.photoUrl]]];
}
return _photo;
}
#end
photo getter is invoked using gcd:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
UIImage *cellImage = model.photo;
});
On line
_photo = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.photoUrl]]];
Instruments shows 100% memory leak. As far as I know arc does not work on threads except main thread. So is there any way of fixing this issue?

RestKit Mapping Error "Cannot map a collection of objects onto a non-mutable collection."

Okay, so I have this code that I'm using to map data from a JSON API. Everything runs fine, but then I get this error:
restkit.object_mapping:RKMapperOperation.m:76 Adding mapping error: Cannot map a collection of objects onto a non-mutable collection. Unexpected destination object type '__NSDictionaryI'
Here is the code I'm using for the mapping
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
RKObjectMapping *classMapping = [RKObjectMapping mappingForClass:[GradePeriod class]];
[classMapping addAttributeMappingsFromDictionary: #{
#"period" : #"period",
#"class" : #"name",
#"term" : #"term",
#"teacher" : #"teacher",
#"percent" : #"percent",
#"grade" : #"grade",
#"missing" : #"missing",
#"update" : #"update",
#"detail" : #"url"
}];
// Create a Response Descriptor
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:classMapping
pathPattern: nil
keyPath: #"grades"
statusCodes:[NSIndexSet indexSetWithIndex:200]];
[objectManager addResponseDescriptor:responseDescriptor];
objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
NSDictionary *queryParams;
queryParams = [NSDictionary dictionaryWithObjectsAndKeys:username, #"username", password, #"password", nil];
// Retrieve the Data
[objectManager postObject:queryParams
path:#""
parameters:queryParams
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
grades = [NSMutableArray arrayWithArray: [mappingResult array]];
NSLog(#"Loaded Grades: %#", grades);
[self.tableView reloadData];
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
// Stuff removed for easier reading
}];
Grades is an NSMutableArray
#property (nonatomic, retain) NSMutableArray *grades;
GradePeriod is defined like this
#property (strong, nonatomic) NSString *period;
#property (strong, nonatomic) NSString *name;
#property (strong, nonatomic) NSString *term;
#property (strong, nonatomic) NSString *teacher;
#property (strong, nonatomic) NSString *percent;
#property (strong, nonatomic) NSString *grade;
#property (strong, nonatomic) NSString *missing;
#property (strong, nonatomic) NSString *update;
#property (strong, nonatomic) NSString *url;
I'm not sure what I'm doing wrong.
Thanks so much!
I upgraded to the latest version of RestKit and it fixed itself.

setting Array in model-class from NSArrayController

How do I set the array in my model-class ValueItem with the content of an NSArrayControllerin my AppDelegate class:
#interface AppDelegate : NSObject <NSApplicationDelegate>
{
ValueItem *vi;
}
and:
#implementation AppDelegate
{
ValueItem *array = [[ValueItem alloc]init];
[array setValueArray:[outArrayController arrangedObjects]];
NSArray *testArray2 = vi.valueArray; // !!!getter or setter doesn't work!!!
NSLog(#"test array 2 is:%#", testArray2);
}
NSLog returns NULL. What do I miss here?
(valueArray is initialized with #property and #synthesize)
ValueItem.h:
#import <Foundation/Foundation.h>
#interface ValueItem : NSObject
{
NSNumber *nomValue;
NSNumber *tolerancePlus;
NSNumber *toleranceMinus;
NSMutableArray *valueArray;
}
#property (readwrite, copy) NSNumber *nomValue;
#property (readwrite, copy) NSNumber *tolerancePlus;
#property (readwrite, copy) NSNumber *toleranceMinus;
#property (nonatomic, retain) NSMutableArray *valueArray;
#end
ValueItem.m:
#import "ValueItem.h"
#implementation ValueItem
#synthesize nomValue, tolerancePlus, toleranceMinus;
#synthesize valueArray;
-(NSString*)description
{
return [NSString stringWithFormat:#"nomValue is: %# | tolerancePlus is: %# | toleranceMinus is: %#", nomValue, tolerancePlus, toleranceMinus];
}
#end
Solution: Need to make sure you're dealing with the AppDelegate's vi property:
// We need to make sure we're manipulating the AppDelegate's vi property!
self.vi = [[ValueItem alloc]init];
[vi setValueArray:[outArrayController arrangedObjects]];
NSArray *testArray2 = vi.valueArray; // !!!getter or setter doesn't work!!!
NSLog(#"test array 2 is:%#", testArray2);
Explanation :
On the first two lines you were manipulating the array ValueItem variable, then attempting to set testArray2 to the value of the uninitialized vi ValueItem variable.
// This is a new variable, unrelated to AppDelegate.vi
ValueItem *array = [[ValueItem alloc]init];
[array setValueArray:[outArrayController arrangedObjects]];
// Here, AppDelegate.vi hasn't been initialized, so valueArray *will* be null!
NSArray *testArray2 = vi.valueArray;
NSLog(#"test array 2 is:%#", testArray2);

NSAttributedString as a Transformable Attribute in Core Data Entity

In the Core Data Programming Guide under "Transformable Attributes" here.
It is stated "You can now use the attribute as you would any other standard attribute, as illustrated in the following code fragment:"
The follow line of code is listed newEmployee.favoriteColor = [NSColor redColor];
I am trying to do something similar in my code but it doesn't work. Here is my code:
In Entry.h:
#interface Entry : NSManagedObject
{
}
#property (nonatomic, retain) NSAttributedString * contentString;
#property (nonatomic, retain) NSDate * date;
#property (nonatomic, retain) NSManagedObject * journal;
#end
and in Entry.m:
#implementation Entry
#dynamic contentString;
#dynamic date;
#dynamic journal;
- (void)awakeFromInsert {
[super awakeFromInsert];
self.date = [NSDate date];
}
#end
Elsewhere I have this code:
Entry *newEntry =
[NSEntityDescription insertNewObjectForEntityForName:#"Entry"
inManagedObjectContext:[self managedObjectContext]];
newEntry.contentString = [[[NSAttributedString alloc] initWithString:#"MyString"] autorelease];
newEntry.journal = self.journal;
The line
newEntry.contentString = [[[NSAttributedString alloc] initWithString:#"MyString"] autorelease];
is equivalent to
newEmployee.favoriteColor = [NSColor redColor];
As far as I can tell however this doesn't work. I get a runtime error:
2010-10-13 09:02:08.577 JournalMaker[2437:a0f] Cannot create NSData
from object MyString{ } of class NSConcreteAttributedString
I have no idea what this error message is supposed to mean. Can someone explain?

Resources