How to use parametrized method with NSNotificationCenter? - objective-c

I'd like to pass dict to the method processit. But once I access the dictionary, I get EXC__BAD_INSTRUCTION.
NSNotificationCenter *ncObserver = [NSNotificationCenter defaultCenter];
[ncObserver addObserver:self selector:#selector(processit:) name:#"atest"
object:nil];
NSDictionary *dict = [[NSDictionary alloc]
initWithObjectsAndKeys:#"testing", #"first", nil];
NSString *test = [dict valueForKey:#"first"];
NSNotificationCenter *ncSubject = [NSNotificationCenter defaultCenter];
[ncSubject postNotificationName:#"atest" object:self userInfo:dict];
In the recipient method:
- (void) processit: (NSDictionary *)name{
NSString *test = [name valueForKey:#"l"]; //EXC_BAD_INSTRUCTION occurs here
NSLog(#"output is %#", test);
}
Any suggestions on what I'm doing wrong?

You will receive an NSNotification object, not an NSDictionary in the notification callback.
Try this:
- (void) processit: (NSNotification *)note {
NSString *test = [[note userInfo] valueForKey:#"l"];
NSLog(#"output is %#", test);
}

Amrox is absolutely right.
One can also use Object (instead of userInfo) for the same as below:
- (void) processit: (NSNotification *)note {
NSDictionary *dict = (NSDictionary*)note.object;
NSString *test = [dict valueForKey:#"l"];
NSLog(#"output is %#", test);
}
In this case your postNotificationName:object will look like:
[[NSNotificationCenter defaultCenter] postNotificationName:#"atest" object:dict];

You will receive an NSNotification object, not an NSDictionary in the notification callback.
(void) processit: (NSNotification *)note {
NSDictionary dict = (NSDictionary)note.object;
NSString *test = [dict valueForKey:#"l"];
NSLog(#"output is %#", test);
}

Related

setting an array from another view in objective c

I have a class which can be accessed from all other pages just like facebook chat head bubble.Its a cart in my application.Items to the cart could be added from different views. HAve tried with NSNotification and is not working.The array inside the cart view is gettig as null.Any help?What i tried is:
-(IBAction)addToCart:(id)sender{
NSMutableArray *itemToCart=[[NSMutableArray alloc]init];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:gearImgView.image forKey:#"equipImage"];
[dict setObject:nameLbl.text forKey:#"name"];
[dict setObject:priceLbl.text forKey:#"price"];
[dict setObject:self.shopifyIDString forKey:#"shopifyID"];
[itemToCart addObject:dict];
[[NSNotificationCenter defaultCenter] postNotificationName:#"equipmentSelected" object:nil userInfo:dict];
}
And in the cart view,
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(loadEquipmentview:) name:#"equipmentSelected" object:nil];
[super viewDidLoad];
}
-(void)loadEquipmentview:(NSNotification *)notification{
NSDictionary *dict = [notification userInfo];
NSString *shopifyID = [dict objectForKey:#"shopifyID"];
NSLog(#"%#",dict);
}
Your array exist just in the addCart method's scope. try like this :
-(IBAction)addToCart:(id)sender{
NSMutableArray *itemToCart=[[NSMutableArray alloc]init];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:gearImgView.image forKey:#"equipImage"];
[dict setObject:nameLbl.text forKey:#"name"];
[dict setObject:priceLbl.text forKey:#"price"];
[dict setObject:self.shopifyIDString forKey:#"shopifyID"];
[itemToCart addObject:dict];
// Create an other dictionnary to hold the array of dictionary
NSMutableDictionary *otherDict = [NSMutableDictionary dictionary];
otherDict[#"yourArrayKey"] = itemToCart;
// The you post the otherDict
[[NSNotificationCenter defaultCenter] postNotificationName:#"equipmentSelected" object:nil userInfo:otherDict]; //be careful here, you should post the otherDict and not the dic.
}
and you retrieve your array, you can do like this :
-(void)loadEquipmentview:(NSNotification *)notification{
NSDictionary *dict = [notification userInfo];
NSMutableArray *array = dic[#"yourArrayKey"];
....
}
If you aren't using ARC, you might want to change the following line,
NSDictionary *dict = [notification userInfo];
To;
NSDictionary *dict = [notification userInfo] retain];

Failed to load UIDocuments in separate devices

I have created a UIDocument to wrap a custom object. The UIDocument is successfully saving to iCloud, and I am successfully loading each UIDocument when I run the app each time. However, when I attempt to run the app on a new device (iPhone 5) it will not load any UIDocument from iCloud, but I can check iCloud under Settings and see the files that are saved under my app. Does anyone have some steps to check to see why one device (iPhone 4) can load and the other (iPhone 5) cannot? I also cannot create a new UIDocument from the iPhone 5 device.
EDIT
- (void)loadObjects
{
if (!self.objects)
{
self.objects = [[NSMutableArray alloc] init];
}
NSURL *baseURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (baseURL)
{
self.query = [[NSMetadataQuery alloc] init];
[self.query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K like 'Object_*'", NSMetadataItemFSNameKey];
[self.query setPredicate:predicate];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:#selector(queryDidFinish:) name:NSMetadataQueryDidFinishGatheringNotification object:self.query];
[nc addObserver:self selector:#selector(queryDidUpdate:) name:NSMetadataQueryDidUpdateNotification object:self.query];
[self.query startQuery];
}
}
- (void)queryDidFinish:(NSNotification *)notification
{
[self processQueryResults:notification.object];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:notification.object];
self.query = nil;
}
- (void)queryDidUpdate:(NSNotification *)notification
{
[self processQueryResults:notification.object];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:notification.object];
self.query = nil;
}
- (void)processQueryResults:(NSMetadataQuery *)query
{
[query disableUpdates];
[query stopQuery];
[self.objects removeAllObjects];
[query.results enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSURL *documentURL = [(NSMetadataItem *)obj valueForAttribute:NSMetadataItemURLKey];
ObjectDocument *document = [[ObjectDocument alloc] initWithFileURL:documentURL];
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
[self.objects addObject:document];
[self sortObjects];
[self.tableView reloadData];
}
}];
}];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)save:(Object *)object
{
NSURL *baseURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (baseURL)
{
NSURL *documentsURL = [baseURL URLByAppendingPathComponent:#"Documents"];
NSURL *documentURL = [documentsURL URLByAppendingPathComponent:[NSString stringWithFormat:#"Object_%f", [object.date timeIntervalSince1970]]];
TVBFlightDocument *document = [[ObjectDocument alloc] initWithFileURL:documentURL];
document.object = object;
[document saveToURL:documentURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
NSLog(#"Save succeeded.");
[_objects addObject:document];
[self sortObjects];
} else {
NSLog(#"Save failed.");
}
}];
}
}
The app on the iPhone 5 will not load the objects stored in iCloud, but iPhone 4 will load the objects from the iCloud documents.

How to Sync an NSDocument from Mac osx to iPad/iPhone with iCloud

I have seen iCloud Document sample code for iOS and I used it to sync a uidocument to and from iCloud and now I am trying to sync iCloud with an nsdocument on a Mac OSX app which doesn't have UIDocument.
I tried to change UIDocument to NSDocument but all the methods of syncing with icloud are different. I haven't found any sample code or tutorials except for the documentation from apple which is very confusing and not well written.
For example, the method below, from UIDocument on iOS does not exist in NSDocument on OS X:
//doc is an instance of subclassed UIDocument
[doc openWithCompletionHandler:nil];
The Apple Documentation provides this code for OS X:
- (void)checkIfCloudAvaliable {
NSURL *ubiquityContainerURL = [[[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil]
URLByAppendingPathComponent:#"Documents"];
if (ubiquityContainerURL == nil) {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
NSLocalizedString(#"iCloud does not appear to be configured.", #""),
NSLocalizedFailureReasonErrorKey, nil];
NSError *error = [NSError errorWithDomain:#"Application" code:404
userInfo:dict];
[self presentError:error modalForWindow:[self windowForSheet] delegate:nil
didPresentSelector:NULL contextInfo:NULL];
return;
}
dest = [ubiquityContainerURL URLByAppendingPathComponent:
[[self fileURL] lastPathComponent]];
}
- (void)moveToOrFromCloud {
dispatch_queue_t globalQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalQueue, ^(void) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error = nil;
// Move the file.
BOOL success = [fileManager setUbiquitous:YES itemAtURL:[self fileURL]
destinationURL:dest error:&error];
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (! success) {
[self presentError:error modalForWindow:[self windowForSheet]
delegate:nil didPresentSelector:NULL contextInfo:NULL];
}
});
});
[self setFileURL:dest];
[self setFileModificationDate:nil];
}
How can I sync between iOS and OS X (because NSDocument does not exists on iOS, and UIDocument does not exist on OS X)? Does anyone know where I can find a sample for Mac OSX (NSDocument syncing)?
I managed to get it working! Here's my code from the subclassed nsdocument file on OS X:
Header file:
#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#interface subclassedNSDocument : NSDocument
#property (strong) NSData *myData;
#end
Implementation file:
- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
BOOL readSuccess = NO;
if (data)
{
readSuccess = YES;
[self setMyData:data];
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"dataModified"
object:self];
return readSuccess;
}
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
if (!myData && outError) {
*outError = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSFileWriteUnknownError userInfo:nil];
}
return myData;
}
and in the AppDelegate.m file:
#define kFILENAME #"mydocument.dox"
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSURL *ubiq = [[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil];
if (ubiq) {
NSLog(#"iCloud access at %#", ubiq);
// TODO: Load document...
[self loadDocument];
}
else
{
NSLog(#"No iCloud access");
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(dataReloaded:)
name:#"dataModified" object:nil];
}
- (void)update_iCloud
{
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:kFILENAME];
self.doc.myData = [NSKeyedArchiver archivedDataWithRootObject:[#"Your Data Array or any data", nil]];
[self.doc saveToURL:ubiquitousPackage ofType:#"dox" forSaveOperation:NSSaveOperation error:nil];
}
- (void)loadData:(NSMetadataQuery *)query {
if ([query resultCount] == 1) {
NSMetadataItem *item = [query resultAtIndex:0];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
NSLog(#"url = %#",url);
subclassedNSDocument *doc = [[subclassedNSDocument alloc] initWithContentsOfURL:url ofType:#"dox" error:nil];
[doc setFileURL:url];
self.doc = doc;
}
else {
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:kFILENAME];
dataUrls *doc = [[dataUrls alloc] init];
[self.doc setFileURL:ubiquitousPackage];
self.doc = doc;
[self.doc saveToURL:ubiquitousPackage ofType:#"dox" forSaveOperation:NSSaveOperation error:nil];
}
}
- (void)queryDidFinishGathering:(NSNotification *)notification {
NSMetadataQuery *query = [notification object];
[query disableUpdates];
[query stopQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:query];
_query = nil;
[self loadData:query];
}
- (void)loadDocument {
NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
_query = query;
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *pred = [NSPredicate predicateWithFormat: #"%K == %#", NSMetadataItemFSNameKey, kFILENAME];
[query setPredicate:pred];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:query];
[query startQuery];
}
- (void)dataReloaded:(NSNotification *)notification
{
self.doc = notification.object;
NSArray *arrFromCloud = [NSKeyedUnarchiver unarchiveObjectWithData:self.doc.myData];
//Update you UI with new data
}
The only thing that I haven't got working is that if I change the data of the document on the iPad, the Mac app doesn't call the readFromData method for to update from iCloud, does anyone know what I am missing?
On iOS, the equivalent method, loadFromContents, is called automatically on every change of the UIDocument in iCloud. On OS X the readFromData is called once on load but never called again.
Hope my code can help, for me it is working one way from Mac to iPad.
I think NSMetadataQueryDidUpdateNotification is what you are looking for to detect document update.
This can be used just like NSMetadataQueryDidFinishGatheringNotification.
If you are dealing with files in addition to core data. Here is a better tutorial
http://samvermette.com/312

applicationWillResignActive notification uncaught on device

I'm trying to save a simple string on a simple .plist file when the application is closing.
This is my code:
- (void)viewDidLoad {
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
self.kmOld.text = [array objectAtIndex:0];
[array release];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:NULL];
[super viewDidLoad];
}
Then follow the applicationWillResignActive method:
- (void)applicationWillResignActive:(NSNotification *)notification {
NSString *text = [[NSString alloc]initWithFormat:#"%#",kmNew.text];
NSLog(#"%#",text);
if ([text intValue]>0) {
NSArray *array = [[NSArray alloc] initWithObjects:text, nil];
BOOL success = [array writeToFile:[self dataFilePath] atomically:YES];
NSLog(#"%d",success);
[array release];
}
[text release];
}
This work fine on the simulator, but it seems to be ignored by the device...
Where is the problem? Thanks...
Take a look at http://www.cocoanetics.com/2010/07/understanding-ios-4-backgrounding-and-delegate-messaging/ for a good overview of the UIApplication lifecycle. Depending on the iOS version your app is running on and the action causing your app to terminate/background you may not be listening for the correct notification and may need to observe UIApplicationWillTerminateNotification as well.

NSNotificationCenter notifications not sent/received

// Question was answered, basicly I should sleep more / code less :)
When my app starts i first load a splash screen, this splashscreen will start a dataDownload when the screen itself is done loading:
Splash.m
#implementation Splash
- (id) init
{
self = [super init];
_lblFunds = [[UILabel alloc] initWithFrame:CGRectMake(350, 330, 324,28)];
_lblFunds.numberOfLines = 1;
[_lblFunds setFont:[UIFont systemFontOfSize:24.0]];
[_lblFunds setTextAlignment: UITextAlignmentCenter];
[_lblFunds setText:#".. Fondsen .."];
[self.view addSubview:_lblFunds];
_lblObjects = [[UILabel alloc] initWithFrame:CGRectMake(350, 360, 324,28)];
_lblObjects.numberOfLines = 1;
[_lblObjects setFont:[UIFont systemFontOfSize:24.0]];
[_lblObjects setTextAlignment: UITextAlignmentCenter];
[_lblObjects setText:#".. Vastgoed Objecten .."];
[self.view addSubview:_lblObjects];
_lblCustomers = [[UILabel alloc] initWithFrame:CGRectMake(350, 390, 324,28)];
_lblCustomers.numberOfLines = 1;
[_lblCustomers setFont:[UIFont systemFontOfSize:24.0]];
[_lblCustomers setTextAlignment: UITextAlignmentCenter];
[_lblCustomers setText:#".. Clienten .."];
[self.view addSubview:_lblCustomers];
return self;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(fundsLoaded) name:#"FundsDone" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(customersLoaded) name:#"CustomersDone" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(objectsLoaded) name:#"ObjectsDone" object:nil];
}
- (void) fundsLoaded
{
[_lblFunds setText:[NSString stringWithFormat:#"Fondsen geladen: %d",[[DataManager sharedInstance] fundsCount]]];
}
- (void) objectsLoaded
{
[_lblObjects setText:[NSString stringWithFormat:#"Vastgoed Objecten geladen: %d",[[DataManager sharedInstance] objectsCount]]];
}
- (void) customersLoaded
{
[_lblCustomers setText:[NSString stringWithFormat:#"Clienten geladen: %d",[[DataManager sharedInstance] customersCount]]];
}
- (void) viewDidLoad
{
[super viewDidLoad];
[[DataManager sharedInstance] getData];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
The DataManager will then proceed to use its instance of DataLoader to load and parse the data in a seperate thread, whenever data is parsed and stored away a Notification is sent from the DataLoader. If worked with the Notifications a lot before but this time it just will not work and I cannot seem to figure out why not. There is no error or anything, but the functions as set in the observers are never called. Any ideas on what is wrong are very much welcome, I have read quite a few threads on here, and other sites but haven't found my answer yet.
DataManager.m
#implementation DataManager
static DataManager* _dataManager = nil;
static DataLoader *_dataLoader = nil;
static bool _dataLoaded = FALSE;
- (int) fundsCount
{
return _dataLoader.funds_count;
}
- (int) objectsCount
{
return _dataLoader.objects_count;
}
- (int) customersCount
{
return _dataLoader.customers_count;
}
+ (DataManager *) sharedInstance{
#synchronized([DataManager class])
{
if(!_dataManager)
{
_dataManager = [[super alloc] init];
_dataLoader = [[DataLoader alloc] init];
}
return _dataManager;
}
return nil;
}
- (void) loadDataSucces
{
_dataLoaded = TRUE;
}
- (void) _getData
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if(_dataLoader)
{
[_dataLoader loadData];
} else
{
NSLog(#"DataLoader not initialized");
}
[pool drain];
}
- (void) getData
{
[NSThread detachNewThreadSelector:#selector(_getData) toTarget:self withObject:nil];
}
#end
DataLoader.m
- (void) parseData: (NSString *) jsonString
{
NSError *err;
SBJsonParser *parser = [[SBJsonParser alloc] init];
id object = [parser objectWithString:jsonString error:&err];
[jsonString release];
if (!object) {
} else {
//funds
id funds = [object objectForKey:#"fondsen"];
[self deleteAllEntitiesOfType:#"Fund"];
int nr = 0;
for (NSDictionary *i in funds)
{
NSString *naam = [i objectForKey:#"naam"];
if([naam length] > 2)
{
NSManagedObjectContext *context = [(CatalogusAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
Fund *f = [NSEntityDescription insertNewObjectForEntityForName:#"Fund" inManagedObjectContext: context];
NSString *integertje = [i objectForKey:#"oid"];
int in = [integertje integerValue];
[f setOid: [NSNumber numberWithInt: in ]];
[f setNaam: naam];
NSError *error = nil;
if( ![context save: &error ])
{
NSLog(#"Error: %#", [[error userInfo] valueForKey:#"ErrorString"]);
} else
{
nr++;
}
}
}
funds_count = nr;
[[NSNotificationCenter defaultCenter] postNotificationName:#"FundsDone" object:nil];
//objects
if( true )
{
id objects = [object objectForKey:#"vastgoedobjecten"];
[self deleteAllEntitiesOfType:#"Object"];
nr = 0;
NSManagedObjectContext *context = [(CatalogusAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
for (NSDictionary *i in objects)
{
Object *o = [NSEntityDescription insertNewObjectForEntityForName:#"Object" inManagedObjectContext: context];
[o setFondsOid:[NSNumber numberWithInt: [ [i objectForKey:#"fondsOid"] integerValue] ]];
[o setOid: [NSNumber numberWithInt: [ [i objectForKey:#"oid"] integerValue] ]];
[o setAdres:[i objectForKey:#"adres"]];
[o setPostcode:[i objectForKey:#"postcode"]];
[o setPlaats: [ i objectForKey:#"plaats"]];
[o setProvincie:[i objectForKey:#"provincie"]];
[o setStatus:[i objectForKey:#"status"]];
[o setSegment:[i objectForKey:#"segment"]];
[o setOppervlakte:[NSNumber numberWithInt: [ [i objectForKey:#"oppervlakte"] integerValue] ]];
[o setBelangrijksteHuurder:[i objectForKey:#"belangrijksteHuurder"]];
[o setWeging:[i objectForKey:#"weging"]];
[o setLongitude:[NSNumber numberWithDouble: [ [i objectForKey:#"longitude"] doubleValue] ]];
[o setLatitude:[NSNumber numberWithDouble: [ [i objectForKey:#"latitude"] doubleValue] ]];
NSError *error = nil;
if( ![context save: &error ])
{
NSLog(#"Error: %#", [[error userInfo] valueForKey:#"ErrorString"]);
} else
{
nr++;
}
}
objects_count = nr;
NSLog(#"ObjectsLoaded");
[[NSNotificationCenter defaultCenter] postNotificationName:#"ObjectsDone" object:nil];
}
//customers
if( true )
{
id custs = [object objectForKey:#"klanten"];
[self deleteAllEntitiesOfType:#"Customer"];
nr = 0;
NSManagedObjectContext *context = [(CatalogusAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
for (NSDictionary *i in custs)
{
Customer *c = [NSEntityDescription insertNewObjectForEntityForName:#"Customer" inManagedObjectContext: context];
[c setOid: [NSNumber numberWithInt: [ [i objectForKey:#"oid"] integerValue] ]];
[c setFondsOid:[NSNumber numberWithInt: [ [i objectForKey:#"fondsOid"] integerValue] ]];
[c setNaam: [i objectForKey:#"naam"]];
NSError *error = nil;
if( ![context save: &error ])
{
NSLog(#"Error: %#", [[error userInfo] valueForKey:#"ErrorString"]);
} else
{
nr++;
}
}
customers_count = nr;
[[NSNotificationCenter defaultCenter] postNotificationName:#"CustomersDone" object:nil];
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"DataReady" object:nil];
}
- (void) loadData{
NSString *urlString = #"URL";
NSDate *startDownload = [NSDate date];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *dataFeed = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
if(error){
NSString *d = [ error description ];
NSLog(#"error: %#",d);
} int bytes = [dataFeed length];
NSDate *endDownload = [NSDate date];
NSString *data = [[NSString alloc] initWithData:[NSData decompress:dataFeed] encoding:NSStringEncodingConversionExternalRepresentation];
int string = [data length];
NSDate *endDecompress = [NSDate date];
NSLog(#"Download data: %f - Decompress: %f - BytesDownloaded: %d", [endDownload timeIntervalSinceDate:startDownload], [endDecompress timeIntervalSinceDate:endDownload], bytes);
[[NSNotificationCenter defaultCenter] postNotificationName:#"DownloadDone" object:nil];
[self parseData:data];
}
In init, you should put your registration code BEFORE the return statement. Otherwise it will never run.
Cheers!