NSMutableArray randomly releasing objects - ios

With my app the user can record a drive using LocationManager while on the road for different calculation purposes. These calculations are done in the Class Calculator. This usually works fine except for sometimes when apparently the NSMutableArrays energyArray and energyOnlyDriveArray looses all if its stored values which are then written as nil int Core Data.
Here is the code:
DriveView Loads
DriveView.h
#interface DriveView : UIScrollView <ADBannerViewDelegate,CLLocationManagerDelegate,CalculatorDelegate>
{
Calculator *calculator;
}
#property (nonatomic, strong) Calculator *calculator;
DriveView.m
#implementation DriveView
#synthesize calculator = _calculator;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_calculator = [[Calculator alloc]init];
_calculator.delegate = self;
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
[_calculator locationManagerDidUpdateLocations:locations];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
[_calculator locationManagerDidFailWithError:error];
}
User starts recording
DriveView tells the location manager to start updating locations and calls initData and initCarData when the user starts to record a drive.
Calculator.h
#interface Calculator : NSObject {
#private
NSMutableArray *energyArray;
NSMutableArray *energyOnlyDriveArray;
}
#property (strong, nonatomic) id <CalculatorDelegate> delegate;
#property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, strong) dispatch_queue_t queue;
#property (nonatomic, strong) NSMutableArray *alt_filtered;
#property (nonatomic, strong) NSMutableArray *energyArray;
#property (nonatomic, strong) NSMutableArray *energyOnlyDriveArray;
#property (nonatomic, strong) NSMutableDictionary *powerVectorDict;
#property (nonatomic, strong) NSMutableArray *carSpecificData;
- (void)initData;
- (void)initCarData;
...
Calculator.m
#implementation Calculator
#synthesize managedObjectContext = __managedObjectContext;
#synthesize energyArray = _energyArray;
#synthesize energyOnlyDriveArray = _energyOnlyDriveArray;
- (id)init
{
if (self = [super init])
{
_queue = dispatch_queue_create(NULL, NULL);
}
return self;
}
- (void)initData
{
self.managedObjectContext = [kDelegate managedObjectContext];
}
- (void)initCarData
{
_energyArray = [[NSMutableArray alloc]init]; //stores the energy values
_energyOnlyDriveArray = [[NSMutableArray alloc]init]; //stores the energy values
_carSpecificData = [[NSMutableArray alloc]init];
_alt_filtered = [[NSMutableArray alloc]init];
for (int i = 0; i < [[[Cars manager]carsList] count]; i++) {
[_energyArray addObject:[NSNumber numberWithFloat:0.0f]];
[_energyOnlyDriveArray addObject:[NSNumber numberWithFloat:0.0f]];
[_carSpecificData addObject:[NSDictionary new]];
}
....
}
- (void)locationManagerDidUpdateLocations:(NSArray *)locations
{
CLLocation *newLocation = [locations lastObject];
if ((newLocation.horizontalAccuracy > 0) && (newLocation.verticalAccuracy > 0) && (newLocation.horizontalAccuracy < 100) && (newLocation.verticalAccuracy < 100))
{
--> Some code and then `launchAlgorithm:`
}
}
- (void)launchAlgorithm:(Drive*)drive
{
UIApplication* app = [UIApplication sharedApplication];
// Request permission to run in the background. Provide an // expiration handler in case the task runs long.
UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
bgTask = [app beginBackgroundTaskWithExpirationHandler: ^{
[app endBackgroundTask:bgTask];
}];
dispatch_async(_queue, ^{
#autoreleasepool {
for (int i = 0; i < [[[Cars manager]carsList] count]; i++) {
[self processAlgorithmResults:[Algorithm that calculation and returns NSDictionary]];
}
if (bgTask != UIBackgroundTaskInvalid) {
dispatch_async(_queue, ^{
[app endBackgroundTask:bgTask];
});
}
}
});
- (void)processAlgorithmResults:(NSMutableDictionary *)driverProfile
{
// write energy into array
float energyValue = [[_energyArray objectAtIndex:i]floatValue] + [[driverProfile objectForKey:#"EVerbrauch"] floatValue];
[_energyArray replaceObjectAtIndex:i withObject:[NSNumber numberWithFloat:energyValue]];
float energyOnlyDriveValue = [[_energyOnlyDriveArray objectAtIndex:i]floatValue] + [[driverProfile objectForKey:#"EVerbrauchOnlyDrive"] floatValue];
[_energyOnlyDriveArray replaceObjectAtIndex:i withObject:[NSNumber numberWithFloat:energyOnlyDriveValue]];
// set power value
NSMutableArray *powerValueArray = [NSMutableArray arrayWithArray:[_powerVectorDict objectForKey:[NSNumber numberWithInteger:i]]];
[powerValueArray addObject:[[driverProfile objectForKey:#"P"]valueForKey:#"Pel_drive"]];
[_powerVectorDict setObject:powerValueArray forKey:[NSNumber numberWithInteger:i]];
}
AFTER THE DRIVE IS DONE EVERYTHING IS SAVED LIKE THIS:
- (void)saveHistory
{
for (int i = 0; i < [[[Cars manager]carsList] count]; i++) {
// power array of the car
NSMutableArray *powerArray = [_powerVectorDict objectForKey:[NSNumber numberWithInt:i]];
History *history = (History *)[NSEntityDescription insertNewObjectForEntityForName:#"History" inManagedObjectContext:self.managedObjectContext];
history.driveID = [[Settings manager]lastDriveID];
history.distance = [NSNumber numberWithFloat:_totalDistance];
history.vMax = [NSNumber numberWithFloat:_maxSpeed];
history.driveDate = firstTime;
history.sentToServer = [NSNumber numberWithBool:NO];
history.vMean = [NSNumber numberWithFloat:_avgSpeed];
history.energy = [NSNumber numberWithFloat:[[_energyArray objectAtIndex:i]floatValue]];
history.energy_onlyDrive = [NSNumber numberWithFloat:[[_energyOnlyDriveArray objectAtIndex:i]floatValue]];
history.car = [[[[Cars manager]carsList] objectAtIndex:i] objectForKey:#"name"];
history.carID = [NSNumber numberWithInt:i];
history.area = [[[[Cars manager]carsList] objectAtIndex:i] objectForKey:#"area"];
history.cw = [[[[Cars manager]carsList] objectAtIndex:i] objectForKey:#"cw"];
history.weight = [[[[Cars manager]carsList] objectAtIndex:i] objectForKey:#"weight"];
history.driveDuration = [NSNumber numberWithFloat:[lastTime timeIntervalSinceDate:firstTime]];
history.temperature = [[Settings manager]localTemperature];
history.temperatureSystem = [[Settings manager]temperatureSystem];
history.precision = [NSNumber numberWithFloat:(((float)_totalSignals-(float)_badSignals))/(float)_totalSignals];
history.includeInProfile = [NSNumber numberWithBool:YES];
history.maxPower = [NSNumber numberWithFloat:[[powerArray objectAtIndex:index]floatValue]];
history.lastSentChunk = [NSNumber numberWithFloat:0];
}
if (self.managedObjectContext != nil)
{
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"error: %#",error.description);
NSLog(#"error: %#",error);
}
}
}
Now when I retrieve the data the values for history.energy and history.energy_onlyDrive return nil value.
The app can also run in the background and will do all the calculations there as well.
I hope somebody can help me out here. I really cant see why the arrays are being cleared which seems kind of random because sometimes it happens and sometimes it doesnt. I is also not relevant how long the calculations go. I have it happen when doing a 3 minute drive as well as a 3 hour drive.
Thanks a lot for your help!

Related

Objective-C - Firebase retrieving data from database and populate in table

Database structure
I have a Firebase database setup (please refer to the picture).
I have a "FeedViewController" to display the contents of each post in the database. A user may post one or more posts.
When retrieving these posts from the Firebase snapshot and storing them onto a dictionary, I find that this dictionary's values are not accessible outside of the Firebase's observeEventType function.
My idea was to retrieve these key-value pairs, store them onto a NSObject custom class object (Post *post) and use this object to load the table view for my "FeedViewController". Inside the observeEventType function, I am able to access the object's values, but outside, I'm not. As a result, I don't know how to use these values to populate the table view in my FeedViewController. I understand that this observeEventType function is an asynchronous callback, but I don't know how to access the values of the object and populate my table. I don't have a clue what the dispatch_async(dispatch_get_main_queue() function is doing here. Any help would be highly appreciated. Thanks!
FeedViewController.m
#import "FeedViewController.h"
#import "Post.h"
#import "BackgroundLayer.h"
#import "SimpleTableCell.h"
#import "FBSDKCoreKit/FBSDKCoreKit.h"
#import "FBSDKLoginKit/FBSDKLoginKit.h"
#import "FBSDKCoreKit/FBSDKGraphRequest.h"
#import Firebase;
#import FirebaseAuth;
#import FirebaseStorage;
#import FirebaseDatabase;
#interface FeedViewController()
#property (strong, nonatomic) Post *post;
#end
#implementation FeedViewController
-(void) viewDidLoad {
[super viewDidLoad];
_ref = [[FIRDatabase database] reference];
self.post = [[Post alloc] init];
/*
_idArr = [[NSMutableArray alloc] init];
_postDict = [[NSMutableDictionary alloc] init];
_idDict = [[NSMutableDictionary alloc] init];
_postID = [[NSMutableArray alloc] init];
_userName = [[NSMutableArray alloc] init];
_placeName = [[NSMutableArray alloc] init];
_addressLine1 = [[NSMutableArray alloc] init];
_addressLine2 = [[NSMutableArray alloc] init];
_ratings = [[NSMutableArray alloc] init];
_desc = [[NSMutableArray alloc] init];
_userEmail = [[NSMutableArray alloc] init];
_userIDArray = [[NSMutableArray alloc] init];
*/
[self fetchData];
NSLog(#"Emails: %#", _post.userID);
}
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
CAGradientLayer *bgLayer = [BackgroundLayer blueGradient];
bgLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:bgLayer atIndex:0];
FIRUser *user = [FIRAuth auth].currentUser;
if (user != nil)
{
//fbFirstName.text = user.displayName;
//fbEmail.text = user.email;
NSURL *photoUrl = user.photoURL;
NSString *userID = user.uid;
//NSString *uploadPath = [userID stringByAppendingString:#"/profile_pic.jpg"];
//NSData *data = [NSData dataWithContentsOfURL:photoUrl];
//ProfilePic.image = [UIImage imageWithData:data];
FIRStorage *storage = [FIRStorage storage];
FIRStorageReference *storageRef = [storage referenceForURL:#"gs://foodsteps-cee33.appspot.com"];
NSString *access_token = [[NSUserDefaults standardUserDefaults] objectForKey:#"fb_token"];
FBSDKGraphRequest *friendList = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me?fields=friends"
parameters:nil
tokenString: access_token
version:nil
HTTPMethod:#"GET"];
[friendList startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if(error == nil)
{
//NSLog(#"%#", result);
NSDictionary *dictionary = (NSDictionary *)result;
NSDictionary *dict = [dictionary objectForKey:#"friends"];
_idArray = [[NSMutableArray alloc] init];
for(int i = 0; i < [[dict objectForKey:#"data"] count]; i++) {
[_idArray addObject:[[[dict objectForKey:#"data"] objectAtIndex:i] valueForKey:#"id"]];
}
//NSLog(#"%#", idArray);
}
else {
NSLog(#"%#",error);
}
}];
}
}
-(void) fetchData {
_refHandle = [[_ref child:#"users"] observeEventType:FIRDataEventTypeValue
withBlock:^(FIRDataSnapshot * _Nonnull snapshot)
{
NSDictionary *postDict = snapshot.value;
NSLog(#"%#", postDict);
for( NSString *aKey in [postDict allKeys] )
{
// do something like a log:
_post.userID = aKey;
}
//_post.
//[_post setValuesForKeysWithDictionary:postDict];
[self.tableView reloadData];
}];
NSLog(#"Emails: %#", _post.userID);
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
-(void) viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[_ref child:#"users"] removeObserverWithHandle:_refHandle];
}
#end
Post.m
#import "Post.h"
#implementation Post
- (instancetype)init {
return [self initWithUid:#""
andPostid:#""
andUsername:#""
andDesc:#""
andRatings:#""
andPlacename:#""
andAddressLine1:#""
andAddressLine2:#""
andEmail:#""];
}
- (instancetype)initWithUid:(NSString *)userID
andPostid:(NSString *)postID
andUsername: (NSString *)userName
andDesc:(NSString *)desc
andRatings:(NSString *)ratings
andPlacename: (NSString *)placeName
andAddressLine1: (NSString *)addressLine1
andAddressLine2: (NSString *)addressLine2
andEmail: (NSString *)userEmail {
self = [super init];
if(self) {
self.userID = userID;
self.postID = postID;
self.userName = userName;
self.desc = desc;
self.ratings = ratings;
self.placeName = placeName;
self.addressLine1 = addressLine1;
self.addressLine2 = addressLine2;
self.userEmail = userEmail;
}
return self;
}
#end
Your approach is what I tried to do initially. But I had problems accessing it in cellforrowatindexpath. the thing that works for me is.
- (void)configureDatabase :(NSUInteger)postsAmount{
_ref = [[FIRDatabase database] reference];
// Listen for new messages in the Firebase database
_refHandle = [[[[_ref child:#"posts"]queryOrderedByKey] queryLimitedToLast:postsAmount]observeEventType:FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot *snapshot) {
[_posts insertObject:snapshot atIndex:0];
}];
}
Then in viewdidappear
[self configureDatabase:_numberOfPosts];
then lastly
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FIRDataSnapshot *postsSnapshot = _posts[indexPath.section];
NSDictionary *post = postsSnapshot.value;
//use key values to create your views.
}
also include
#property (strong, nonatomic) NSMutableArray<FIRDataSnapshot *> *posts;
What this does is queries firebase for your values and receives snapshots. those snapshots are then placed in your _posts array and then you can access them in other methods.

can't add the Dynamic values in Pie Carts [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
//
// PieChartTest.m
// Yazaki
//
// Created by apple on 3/25/16.
// Copyright (c) 2016 apple. All rights reserved.
//
#import "PieChartTest.h"
#import "testingvc.h"
#interface PieChartTest ()
#property (strong, nonatomic) NSMutableArray *values;
#property (strong, nonatomic) NSMutableArray *testARYY;
#property (strong, nonatomic) NSMutableArray *labels;
#property (strong, nonatomic) NSMutableArray *colors;
#property (nonatomic) BOOL inserting;
#property (strong, nonatomic) NSArray *colors1;
#property (strong, nonatomic) NSDictionary *serviceResponse;
#property(strong,nonatomic) NSString *item;
#property(strong,nonatomic) NSArray *temp;
#property (strong, nonatomic) NSDictionary *sample;
#end
#implementation PieChartTest
#synthesize dictObject;
#synthesize str1;
#synthesize str2;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *baseURL = [NSString stringWithFormat:#"http://192.168.1.122:8099/YazakiService.svc/SESSION/%#/%#/%#",dictObject,str1,str2];
NSURL *url = [NSURL URLWithString:[baseURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
NSData *responseData =[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
_serviceResponse=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSArray *temp = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
NSDictionary *sample=[temp objectAtIndex:0];
NSString*item=[sample objectForKey:#"COUNTVALUE"];
if( [_serviceResponse objectForKey:#"SESSIONCOUNT"] == nil ||
[[_serviceResponse objectForKey:#"SESSIONCOUNT"] isEqual:[NSNull null]] ){
// do nothing
}else
{
NSArray *temp = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
if ([temp isKindOfClass:[NSArray class]] && temp.count !=0)
{
// value is available
[self.values removeAllObjects];
self.values = [NSMutableArray new];
int i;
for (i=0; i<[temp count]; i++) {
[self.values addObject:[NSString stringWithFormat:#"%#",[[temp objectAtIndex:i] objectForKey:#"COUNTVALUE"]]];
[self.values addObject:[NSString stringWithFormat:#"%#",[[temp objectAtIndex:i] objectForKey:#"SESSIONVALUE"]]];
}
}
}
self.pieChartView.dataSource = self;
self.pieChartView.delegate = self;
self.pieChartView.animationDuration = 0.5;
self.pieChartView.sliceColor = [MCUtil flatWetAsphaltColor];
self.pieChartView.borderColor = [MCUtil flatSunFlowerColor];
self.pieChartView.selectedSliceColor = [MCUtil flatSunFlowerColor];
self.pieChartView.textColor = [MCUtil flatSunFlowerColor];
self.pieChartView.selectedTextColor = [MCUtil flatWetAsphaltColor];
self.pieChartView.borderPercentage = 0.01;
}
- (NSInteger)numberOfSlicesInPieChartView:(MCPieChartView *)pieChartView {
return self.values.count;
}
- (CGFloat)pieChartView:(MCPieChartView *)pieChartView valueForSliceAtIndex:(NSInteger)index {
return [[self.values objectAtIndex:index] floatValue];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)pieChartView:(MCPieChartView*)pieChartView didSelectSliceAtIndex:(NSInteger)index;
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
testingvc *destViewController = (testingvc*)[storyboard instantiateViewControllerWithIdentifier:#"testing"];
self.values = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
// //destViewController = [CategoryVC.destViewController objectAtIndex:0];
NSDictionary *sample=[self.values objectAtIndex:index];
NSString*item=[sample objectForKey:#"SESSIONVALUE"];
//
destViewController.category = item;
destViewController.STATUS =dictObject;
destViewController.fromDate=str1;
destViewController.Todate=str2;
[destViewController setModalPresentationStyle:UIModalPresentationFullScreen];
[self presentViewController:destViewController animated:NO completion:nil];
}
#end
i got the error while select the 4th slice index ...i got the crash of
2016-03-31 11:40:10.582 Yazaki[2150:37777] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 4 beyond bounds [0 .. 3]'
*** First throw call stack:
change this
self.values=[_serviceResponse objectForKey:#"SESSIONCOUNT"];
NSLog(#"got response==%#", self.values);
int i;
for (i=0; i<[self.values count]; i++) {
NSDictionary *exp=[self.values objectAtIndex:i];
_item=[exp objectForKey:#"COUNTVALUE"];
//[self.testARYY addObject:item];
}
[self.values addObject:_item];
into and try
NSArray *temp = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
if (temp.count>0)
{
[self.values removeAllObjects];
self.values = [NSMutableArray new];
for (i=0; i<[temp count]; i++) {
[self.values addObject:[NSString Stringwithformat:#"%#",[[temp objectAtIndex:i] objectForKey:#"COUNTVALUE"]]];
}
}
or use like
Choice-2
NSArray *temp = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
if ([temp isKindOfClass:[NSArray class]] && temp.count !=0)
{
// value is available
[self.values removeAllObjects];
self.values = [NSMutableArray new];
for (i=0; i<[temp count]; i++) {
[self.values addObject:[NSString Stringwithformat:#"%#",[[temp objectAtIndex:i] objectForKey:#"COUNTVALUE"]]];
}
}
Update-2
if( [_serviceResponse objectForKey:#"SESSIONCOUNT"] == nil ||
[[_serviceResponse objectForKey:#"SESSIONCOUNT"] isEqual:[NSNull null]] ){
// do nothing
}else
{
NSArray *temp = [_serviceResponse objectForKey:#"SESSIONCOUNT"];
if ([temp isKindOfClass:[NSArray class]] && temp.count !=0)
{
// value is available
[self.values removeAllObjects];
self.values = [NSMutableArray new];
for (i=0; i<[temp count]; i++) {
[self.values addObject:[NSString Stringwithformat:#"%#",[[temp objectAtIndex:i] objectForKey:#"COUNTVALUE"]]];
}
}
}
You should try to change this line:
return [[self.values objectAtIndex:index] floatValue];
to this
return [[self.values objectAtIndex:index][#"COUNTVALUE"] floatValue];
The error says that you are trying to call the floatValue function on a NSMutableDictionary, from my understanding you should call it on the value stored under the "COUNTVALUE" key of the dictionary.

How to add object in singleton NSMutableArray

I used to store the array data downloaded from the server.
But I can not save them in the singleton array.
It seems without access to the object.
Why ulatitude, ulongitude, uaccuracy, uplacename is nil?...
in .h file
#import <Foundation/Foundation.h>
#interface LocationData : NSObject
{
NSMutableArray *ulatitude;
NSMutableArray *ulongitude;
NSMutableArray *uaccuracy;
NSMutableArray *uplacename;
}
#property (nonatomic, retain) NSMutableArray *ulatitude;
#property (nonatomic, retain) NSMutableArray *ulongitude;
#property (nonatomic, retain) NSMutableArray *uaccuracy;
#property (nonatomic, retain) NSMutableArray *uplacename;
+ (LocationData*) sharedStateInstance;
#end
in .m file
#import "LocationData.h"
#implementation LocationData
#synthesize uaccuracy;
#synthesize ulatitude;
#synthesize ulongitude;
+ (LocationData*) sharedStateInstance {
static LocationData *sharedStateInstance;
#synchronized(self) {
if(!sharedStateInstance) {
sharedStateInstance = [[LocationData alloc] init];
}
}
return sharedStateInstance;
}
#end
use
[manager POST:urlStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#",responseObject);
// json response array
if ([responseObject isKindOfClass:[NSArray class]]) {
NSArray *responseArray = responseObject;
NSDictionary *responseDict = [[NSDictionary alloc] init];
LocationData* sharedState = [LocationData sharedStateInstance];
for(NSUInteger i=0; i < responseArray.count; i++)
{
responseDict = [responseArray objectAtIndex:i];
double dlat = [[responseDict objectForKey:#"lat"] doubleValue];
double dlng = [[responseDict objectForKey:#"lng"] doubleValue];
[[sharedState ulatitude] addObject:[NSString stringWithFormat:#"%f",dlat]];
[[sharedState ulongitude] addObject:[NSString stringWithFormat:#"%f",dlng]];
[[sharedState uaccuracy] addObject:[responseDict objectForKey:#"rad"]];
[[sharedState uplacename] addObject:[responseDict objectForKey:#"place_name"]];
}
You always need to initialize your arrays. You should do somewhere before you try to add something to them:
arrayName = [[NSMutableArray alloc] init];
otherwise you'll always get error because they have not been initialized.
In your case you should override your LocationData init function like this:
- (instancetype)init {
self = [super init];
if (self) {
self.yourArrayName = [[NSMutableArray alloc] init];
// And so on....
}
return self;
}
You need to initialize your object properly. Basically your member variables ("ivars") are pointing to nothing ("nil").
This initializer added to your .m file code do the job.
-(instancetype)init {
if ((self = [super init])) {
self.accuracy = [NSMutableArray array];
self.latitude = [NSMutableArray array];
self.longitude = [NSMutableArray array];
self.uplacename = [NSMutableArray array];
}
return self;
}
As a singleton pattern, I'd prefer the following:
+ (LocationData*) sharedStateInstance {
static LocationData *sharedStateInstance = nil;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
sharedStateInstance = [[LocationData alloc] init];
});
return sharedStateInstance;
}
Although singletons might not be as bad they are often said to be, I don't thing that this is a good usage for them. Your specific problem has nothing to do with that design choice, though.
Try this code. Write getters for your NSMutableArrays.
#import <Foundation/Foundation.h>
#interface LocationData : NSObject
#property (nonatomic, retain) NSMutableArray *ulatitude;
#property (nonatomic, retain) NSMutableArray *ulongitude;
#property (nonatomic, retain) NSMutableArray *uaccuracy;
#property (nonatomic, retain) NSMutableArray *uplacename;
+ (LocationData*) sharedStateInstance;
#end
#import "LocationData.h"
#implementation LocationData
#synthesize uaccuracy = _uaccuracy;
#synthesize ulatitude = _ulatitude;
#synthesize ulongitude = _ulongitude;
+ (LocationData*) sharedStateInstance {
static LocationData *sharedStateInstance;
#synchronized(self) {
if(!sharedStateInstance) {
sharedStateInstance = [[LocationData alloc] init];
}
}
return sharedStateInstance;
}
-(NSMutableArray*)uaccuracy
{
if(_uaccuracy == nil)
{
_uaccuracy = [[NSMutableArray alloc]init];
}
return uaccuracy;
}
-(NSMutableArray*)ulongitude
{
if(_ulongitude == nil)
{
_ulongitude = [[NSMutableArray alloc]init];
}
return ulongitude;
}
-(NSMutableArray*)ulatitude
{
if(_ulatitude == nil)
{
_ulatitude = [[NSMutableArray alloc]init];
}
return ulatitude;
}
-(NSMutableArray*)uplacename
{
if(_uplacename == nil)
{
_uplacename = [[NSMutableArray alloc]init];
}
return uplacename;
}
#end
you don't allocate/init any array...
you can create them in your singleton creation method
+ (LocationData*) sharedStateInstance {
static LocationData *sharedStateInstance;
#synchronized(self) {
if(!sharedStateInstance) {
sharedStateInstance = [[LocationData alloc] init];
sharedStateInstance.ulatitude = [[NSMutableArray alloc] init];
// (add others...)
}
}
return sharedStateInstance;
}
Replace your LocationData.m file with below code , this will work . As you have to alloc and init the array then only you can add object in array
+ (LocationData*) sharedStateInstance {
static LocationData *sharedStateInstance;
#synchronized(self) {
if(!sharedStateInstance) {
sharedStateInstance = [[LocationData alloc] init];
uaccuracy = [[NSMutableArray alloc]init];
ulatitude = [[NSMutableArray alloc]init];
ulongitude = [[NSMutableArray alloc]init];
uplacename = [[NSMutableArray alloc]init];
}
}
return sharedStateInstance;
}

Loading data taking too much time CoreData

I am facing problems when i tries to save 40,000 records into CoreData Entity.
I am getting 40,000 records by consuming the webservice using AFNetworking, the response is in JSON. Than i divide the data into 4 , 10000 record chunks and then assign these 4 chunks to separate NSOperation objects (i have created subclass of NSOperation) and add these NSOperation Objects to NSOperationQueue.
The problem is that this way it is taking too much time to save the data into CoreData. And i want to find a solution where i can load the data very quickly.
This is the code in which i am creating NSOperation objects and adding them to NSOperationQueue.
- (void)casesResponseReceived:(NSArray*)array
{
id responseObject = [array objectAtIndex:0];
NSManagedObjectContext *moc = [array objectAtIndex:1];
NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSArray *response = [responseString JSONValue];
NSString *responseStr = [response JSONRepresentation];
NSRange range = [responseStr rangeOfString:#"["];
int index = 0;
int objectsCount = 5000;
if (range.location == 0) {
NSInteger count = objectsCount;
totalOperationsCount = 0;
completedOperationsCount = 0;
self.myQueue = [[NSOperationQueue alloc] init];
while (count == objectsCount) {
if ((index+count) > [response count]) {
count = [response count] - index;
}
NSArray *subArray = [response subarrayWithRange:NSMakeRange(index, count)];
index += objectsCount;
CaseParseOperation *operation = [[CaseParseOperation alloc] initWithData:subArray MOC:moc];
operation.delegate = self;
totalOperationsCount++;
[self.myQueue addOperation:operation];
}
/*
if (self.delegate && [self.delegate respondsToSelector:#selector(serviceHelperDidCasesReceivedSuccessful:)]) {
[self.delegate serviceHelperDidCasesReceivedSuccessful:self];
}*/
}
else {
if (self.delegate && [self.delegate respondsToSelector:#selector(serviceHelperDidCasesReceivedFailed:)]) {
[self.delegate serviceHelperDidCasesReceivedFailed:self];
}
}}
CaseOperation.h
#class CaseParseOperation;
#protocol CaseParseOperationProtocol <NSObject>
-(void)caseParseOperationDidOperationComplete: (CaseParseOperation*)caseParseOperation;
#end
#interface CaseParseOperation : NSOperation
#property (nonatomic, weak) id<CaseParseOperationProtocol> delegate;
-(id)initWithData:(NSArray*)parseData MOC:(NSManagedObjectContext*)moc;
#end
CaseOperation.m
#interface CaseParseOperation()
#property (nonatomic, copy) NSArray *casesData;
#property (nonatomic, strong) NSManagedObjectContext *mainMOC;
#property (nonatomic, strong) NSManagedObjectContext *localMOC;
#end
#implementation CaseParseOperation
- (id)initWithData:(NSArray*)parseData MOC:(NSManagedObjectContext*)moc
{
self = [super init];
if (self) {
self.casesData = [parseData copy];
self.mainMOC = moc;
}
return self;
}
- (void)main
{
#autoreleasepool {
self.localMOC = [[NSManagedObjectContext alloc] init];
self.localMOC.persistentStoreCoordinator = self.mainMOC.persistentStoreCoordinator;
[[NSNotificationCenter defaultCenter] addObserver: self
selector: #selector(mergeChanges:)
name: NSManagedObjectContextDidSaveNotification
object: self.localMOC];
[self parseData];
}
}
-(void) mergeChanges: (NSNotification*) saveNotification {
dispatch_async(dispatch_get_main_queue(), ^{
[self.mainMOC mergeChangesFromContextDidSaveNotification:saveNotification];
});
if (self.delegate && [self.delegate respondsToSelector:#selector(caseParseOperationDidOperationComplete:)]) {
[self.delegate caseParseOperationDidOperationComplete:self];
}
}
- (void)parseData
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *ent = [NSEntityDescription entityForName:#"Case" inManagedObjectContext:self.localMOC];
fetchRequest.entity = ent;
NSString *predicateString = [NSString stringWithFormat:#"caseNumber == $caseNumber"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
//NSMutableArray *insertedObjects = [[NSMutableArray alloc] init];
for (NSMutableDictionary *dic in self.casesData) {
if (self.isCancelled) {
break;
}
NSString *desc = [dic valueForKey:#"description"];
BOOL enabled = [[dic valueForKey:#"enabled"] boolValue];
NSString *billToCustomerNo = [dic valueForKey:#"billToCustomerNo"];
NSString *caseNo = [dic valueForKey:#"caseNo"];
NSString *billToName = [dic valueForKey:#"billToName"];
NSString *personResponsible = [dic valueForKey:#"personResponsible"];
NSDictionary *variables = #{ #"caseNumber" : caseNo };
fetchRequest.predicate = [predicate predicateWithSubstitutionVariables:variables];
NSArray *matchedObj = [self.localMOC executeFetchRequest:fetchRequest error:nil];
if ([matchedObj count] > 0) {
Case *caseObj = [matchedObj objectAtIndex:0];
caseObj.isEnabled = [NSNumber numberWithBool:enabled];
caseObj.caseDescription = desc;
caseObj.customerNumber = billToCustomerNo;
caseObj.customerName = billToName;
caseObj.personResponsible = personResponsible;
}
else {
/*
Case *caseObj = [[Case alloc] initWithEntity:[NSEntityDescription entityForName:#"Case"
inManagedObjectContext:self.localMOC] insertIntoManagedObjectContext:nil];
caseObj.caseNumber = caseNo;
caseObj.customerName = billToName;
caseObj.customerAddress = #"";
caseObj.customerPhone = #"";
caseObj.caseDescription = desc;
caseObj.customerNumber = billToCustomerNo;
caseObj.isEnabled = [NSNumber numberWithBool:enabled];
caseObj.personResponsible = personResponsible;
[insertedObjects addObject:caseObj];
*/
[Case createObjectWithCaseNumber:caseNo customerName:billToName customerAddress:#"" customerPhone:#"" caseDescription:desc customerNumber:billToCustomerNo isEnabled:enabled personResponsible:personResponsible MOC:self.localMOC];
}
}
/*
if ([insertedObjects count] > 0) {
NSError *error = nil;
BOOL isInserted = [self.localMOC obtainPermanentIDsForObjects:insertedObjects error:&error];
if (error || !isInserted) {
NSLog(#"Error occured");
}
}
*/
if ([self.localMOC hasChanges]) {
[self.localMOC save:nil];
}
}
#end
The first thing to do is run Instruments and find the bottlenecks, as #jrturton recommends.
But there's one huge glaring bottleneck that's apparent from reading the code. To avoid duplicates, you're doing a fetch-- for every incoming instance. With 40k records you'll have to do 40k fetches during the import process, and that's going to be slow no matter what.
You can improve that by processing the data in batches:
Get a bunch of caseNumber values into an array
Do a fetch with a predicate of caseNumber IN %#, with the array as the argument.
Use that array to check for duplicates.
You'll need to experiment a little to see how many "a bunch" is in step 1. Higher numbers mean fewer fetches, which is good for speed. But higher numbers also mean more memory use.
For a more detailed discussion, see Apple's Efficiently Importing Data guide, especially the section named "Implementing Find-or-Create Efficiently".
Thanks guys valuable suggestions. But i have solved that issue by just altering some technique in the parseData function.
-(void)parseData
{
NSString *predicateString = [NSString stringWithFormat:#"caseNumber == $caseNumber"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
NSArray *allCases = [Case getAllCaseObjectsWithMOC:self.localMOC];
for (NSMutableDictionary *dic in self.casesData) {
if (self.isCancelled) {
break;
}
NSString *caseNo = [dic valueForKey:#"caseNo"];
NSDictionary *variables = #{ #"caseNumber" : caseNo };
predicate = [predicate predicateWithSubstitutionVariables:variables];
NSArray *matchedObj = [allCases filteredArrayUsingPredicate:predicate];
if ([matchedObj count] == 0) {
NSString *desc = [dic valueForKey:#"description"];
BOOL enabled = [[dic valueForKey:#"enabled"] boolValue];
NSString *billToCustomerNo = [dic valueForKey:#"billToCustomerNo"];
NSString *billToName = [dic valueForKey:#"billToName"];
NSString *personResponsible = [dic valueForKey:#"personResponsible"];
[Case createObjectWithCaseNumber:caseNo customerName:billToName customerAddress:#"" customerPhone:#"" caseDescription:desc customerNumber:billToCustomerNo isEnabled:enabled personResponsible:personResponsible MOC:self.localMOC];
}
}
if ([self.localMOC hasChanges]) {
[self.localMOC save:nil];
}
}

method not being called since adding parallax image

So i recently implemented parallax images into my app which works great, however this has broken a button which calls a method.
Here is a picture of my storyboard:
http://imgur.com/uIonWrK
Here is my .h code:
#interface _01FirstViewController : UIViewController <UITextFieldDelegate, UIAccelerometerDelegate>{
UIAccelerometer *accelerometer;
float xoof;
float yoff;
float xvelocity;
float yvelocity;
float xaccel;
float yaccel;
}
#property (nonatomic, retain) UIAccelerometer *accelerometer;
#property (weak, nonatomic) IBOutlet UIScrollView *BGScrollView;
#property (weak, nonatomic) IBOutlet UIButton *Track;
#property (weak, nonatomic) IBOutlet UITextField *trackingNumber;
#property (strong, nonatomic) NSDictionary *posts;
#property (strong,nonatomic) NSString *TrackPoint;
#property (strong,nonatomic) NSArray *Path;
#property (strong,nonatomic) NSString *documentFolder;
#property (strong,nonatomic) NSString *filePath;
-(void)parseTrackNo;
-(void)reloadTrackingNumber;
Here is the relevant parts of the .m:
- (void)viewDidLoad
{
_BGScrollView.contentSize = CGSizeMake(_BGScrollView.frame.size.width+30,_BGScrollView.frame.size.width+30);
self.accelerometer = [UIAccelerometer sharedAccelerometer];
self.accelerometer.updateInterval = 0.03;
self.accelerometer.delegate = self;
[NSTimer scheduledTimerWithTimeInterval:-1 target:self selector:#selector(tick) userInfo:nil repeats:YES];
}
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
float xx = -acceleration.x;
float yy = (acceleration.y + 0.5f) *2.0f;
float acceldirX;
if (xvelocity * -1.0f >0){
acceldirX = 1.0;
}
else {
acceldirX = -1.0;
}
float newdirX;
if (xx > 0){
newdirX = 1.0;
}
else {
newdirX = -1.0;
}
float acceldirY;
if (yvelocity * -1.0f >0){
acceldirY = 1.0;
}
else {
acceldirY = -1.0;
}
float newDirY;
if (yy > 0){
newDirY = 1.0;
}
else {
newDirY = -1.0;
}
if (acceldirX == newdirX) xoof = acceleration.x * 30;
if (acceldirY == newDirY) yoff = acceleration.y *30;
}
This is the button that has stopped calling the method:
- (IBAction)Track:(id)sender {
[self parseTrackNo]; //Not calling method
NSLog(#"Button Pressed"); //This gets logged correctly
}
I have tried removing all code changes so i suspect it is something to do with the button being nested inside the view in the storyboard or the delegate changes.
Can anyone point me in the correct direction?
EDIT as requested the code for parseTrackingNo (note this was working perfectly until the parallax changes):
-(void)parseTrackNo
{
_01AppDelegate *appDelegate = (_01AppDelegate *)[[UIApplication sharedApplication] delegate];
//Get Tracking Number from textField
appDelegate.TrackingNumber = _trackingNumber.text;
//Check String isn't empty
if ([_trackingNumber.text isEqual: #""]){
} else{
//Check against Royal Mail API
NSString *trackingURL = [NSString stringWithFormat:#"%#%#", #"http://api.e44.co/tracktrace/", appDelegate.TrackingNumber];
NSURL *royalMail = [NSURL URLWithString:trackingURL];
//Return results
NSData *royalMailResults = [NSData dataWithContentsOfURL:royalMail];
//Parse JSON results
if(royalMailResults != nil)
{
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:royalMailResults options:NSJSONReadingMutableContainers error:&error];
if (error == nil)
//Convert to dictionary/array
self.posts = (NSDictionary *)result;
NSArray *trackRecords = _posts[#"trackRecords"];
//Return keys from posts (Dict)
NSString *response = [self.posts valueForKeyPath:#"response"];
NSLog(#"Response: %#", response);
NSString *returnedTrackingNumber = [self.posts valueForKeyPath:#"trackingNumber"];
NSLog(#"Returned tracking number: %#", returnedTrackingNumber);
NSString *delivered = [self.posts valueForKeyPath:#"delivered"];
NSLog(#"delivered: %#", delivered);
NSString *signature = [self.posts valueForKeyPath:#"signature"];
NSLog(#"Signature: %#", signature);
//Track Records
NSString *Date = [trackRecords valueForKeyPath:#"date"];
NSLog(#"date: %#", Date);
NSString *Time = [trackRecords valueForKeyPath:#"time"];
NSLog(#"time: %#", Time);
NSString *Status = [trackRecords valueForKeyPath:#"status"];
NSLog(#"status: %#", Status);
appDelegate.LocationData = [[trackRecords valueForKey:#"trackPoint"] componentsJoinedByString:#""];
NSLog(#"GeoLocation: %#", appDelegate.LocationData);
//Check for Errors returned
if ([self.posts objectForKey:#"errorMsg"]) {
NSLog(#"ERROR MOTHERFUCKER");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"It appears that you have entered an incorrect tracking number"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alert show];
} else {
[self performSegueWithIdentifier:#"addPackageSegue" sender:self];
}
}
}
}

Resources