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.
Related
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];
}
}
I'm trying to add objects to an NSMutableArray but it keeps giving me this error.:
NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object
I have researched this problem, and I'm not doing anything wrong that past people have done, so I have no idea what's wrong. Here is my code:
Group.h
#property (strong, nonatomic) NSString *custom_desc;
#property (strong, nonatomic) NSMutableArray *attributes; //I define the array as mutable
Group.m
#import "Group.h"
#implementation Group
-(id)init
{
self = [super init];
if(self)
{
//do your object initialization here
self.attributes = [NSMutableArray array]; //I initialize the array to be a NSMutableArray
}
return self;
}
#end
GroupBuilder.m
#import "GroupBuilder.h"
#import "Group.h"
#implementation GroupBuilder
+ (NSArray *)groupsFromJSON:(NSData *)objectNotation error:(NSError **)error
{
NSError *localError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];
if (localError != nil) {
*error = localError;
return nil;
}
NSMutableArray *groups = [[NSMutableArray alloc] init];
NSDictionary *results = [parsedObject objectForKey:#"result"];
NSArray *items = results[#"items" ];
for (NSDictionary *groupDic in items) {
Group *group = [[Group alloc] init];
for (NSString *key in groupDic) {
if ([group respondsToSelector:NSSelectorFromString(key)]) {
[group setValue:[groupDic valueForKey:key] forKey:key];
}
}
[groups addObject:group];
}
for(NSInteger i = 0; i < items.count; i++) {
//NSLog(#"%#", [[items objectAtIndex:i] objectForKey:#"attributes"]);
NSMutableArray *att = [[items objectAtIndex:i] objectForKey:#"attributes"]; //this returns a NSArray object understandable
Group *g = [groups objectAtIndex:i];
[g.attributes addObjectsFromArray:[att mutableCopy]]; //I use mutable copy here so that i'm adding objects from a NSMutableArray and not an NSArray
}
return groups;
}
#end
Use options:NSJSONReadingMutableContainers on your NSJSONSerialization call.
Then all the dictionaries and arrays it creates will be mutable.
According to the error message you are trying to insert an object into an instance of NSArray, not NSMutableArray.
I think it is here:
NSMutableArray *att = [[items objectAtIndex:i] objectForKey:#"attrib`enter code here`utes"]; //this returns a NSArray object understandable
Items is fetched from JSON and therefore not mutable. You can configure JSONSerialization in a way that it creates mutable objects, but how exactly I don't know out of the top of my head. Check the references on how to do that or make a mutable copy:
NSMutableArray *att = [[items objectAtIndex:i] objectForKey:#"attributes"] mutableCopy];
Next try, considering your replies to the first attempt:
#import "Group.h"
#implementation Group
-(NSMutableArray*)attributes
{
return [[super attributes] mutableCopy];
}
#end
I have an NSArray that I fill with SKTexture to animate an animal leaping:
#interface PSFrogNode ()
#property (strong, nonatomic) NSArray *leapFrames;
#end
#implementation PSFrogNode {
}
- (instancetype)init
{
self = [super init];
if (self) {
SKTextureAtlas *frogLeapAtlas = [SKTextureAtlas atlasNamed:kFrogLeapAtlas];
int numImages = frogLeapAtlas.textureNames.count;
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:numImages];
for (int i=1; i <= numImages/2; i++) {
NSString *textureName = [NSString stringWithFormat:#"frogLeap%d", i];
SKTexture *temp = [frogLeapAtlas textureNamed:textureName];
[tempArray addObject:temp];
}
self.leapFrames = [NSArray arrayWithArray:tempArray];
self = [PSFrogNode spriteNodeWithTexture:[self.leapFrames objectAtIndex:0]];
[self setUserInteractionEnabled:NO];
}
return self;
}
- (void)animateFrogLeap
{
[self runAction:[SKAction animateWithTextures:self.leapFrames timePerFrame:0.09 resize:NO restore:YES]];
}
The array self.leapFrames is allocated in the init method but when the scene calls the animateFrogLeap method it's empty (meaning nil).
Why is that?
You want to create the array outside of the init method and then pass it in:
When creating the view
SKTextureAtlas *frogLeapAtlas = [SKTextureAtlas atlasNamed:kFrogLeapAtlas];
int numImages = frogLeapAtlas.textureNames.count;
NSMutableArray *images = [NSMutableArray arrayWithCapacity:numImages];
for (int i=1; i <= numImages/2; i++) {
NSString *textureName = [NSString stringWithFormat:#"frogLeap%d", i];
SKTexture *temp = [frogLeapAtlas textureNamed:textureName];
[images addObject:temp];
}
PSFrogNode *node = [[PSFrogNode alloc] initWithImages:images];
// Now use the node
PSFrogNode.h
-(instancetype)initWithImages:(NSArray *)images;
PSFrogNode.m
#interface PSFrogNode ()
#property (nonatomic, copy) NSArray *leapFrames;
#end
#implementation PSFrogNode
-(instancetype)initWithImages:(NSArray *)images
{
self = [self initWithTexture:[images firstObject]];
if (self) {
_leapFrames = [images copy];
[self setUserInteractionEnabled:NO];
}
return self;
}
As mentioned in my comment, the below line in your original implementation would mean that self would be reassigned, so the line before it (assigning the array to the property) would then be meaning less.
self = [PSFrogNode spriteNodeWithTexture:[self.leapFrames objectAtIndex:0]];
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!
i am developing very simple quiz app
In viewDidLoad i am adding objects in myarray
where ever i nslog myarray values it works fine
but if i try this inside ibaction methods all objects becomes zombie
for 2 days i am stuck in this but can't find it what is wrong.
quiz.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#class dbVals;
#class viewTransition;
#class AppDelegate;
#interface quiz : UIViewController
{
NSMutableArray *myarray;
IBOutlet UITextView *questionTextView_;
IBOutlet UIButton *skipButton_;
IBOutlet UIButton *optionAButton_;
IBOutlet UIButton *optionBButton_;
IBOutlet UIButton *optionCButton_;
NSString *correctAnswer;
int questionNumber;
int score;
IBOutlet UILabel *scoreLabel_;
int totalQuestions;
}
-(void)populate:(int)number;
//#property(nonatomic, retain) NSMutableArray *myarray;
#property (retain, nonatomic) IBOutlet UITextView *questionTextView;
#property (retain, nonatomic) IBOutlet UIButton *skipButton;
#property (retain, nonatomic) IBOutlet UIButton *optionAButton;
#property (retain, nonatomic) IBOutlet UIButton *optionBButton;
#property (retain, nonatomic) IBOutlet UIButton *optionCButton;
#property (retain, nonatomic) IBOutlet UILabel *scoreLabel;
- (IBAction)optionsToAnswer:(id)sender;
- (IBAction)zzz:(id)sender;
#end
quiz.m
#import "quiz.h"
#import "DbVals.h"
#import "viewTransition.h"
#import "AppDelegate.h"
#implementation quiz
#synthesize skipButton=skipButton_;
#synthesize optionAButton=optionAButton_;
#synthesize optionBButton=optionBButton_;
#synthesize optionCButton=optionCButton_;
#synthesize scoreLabel=scoreLabel_;
#synthesize questionTextView=questionTextView_;
//#synthesize myarray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)createEditableCopyOfDatabaseIfNeeded
{
//NSLog(#"Creating editable copy of database");
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"oq.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"oq.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
+(sqlite3 *) getNewDBConnection
{
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"oq.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
//NSLog(#"Database Successfully Opened ");
} else {
NSLog(#"Error in opening database ");
}
return newDBconnection;
}
- (void)viewDidLoad
{
[super viewDidLoad];
questionNumber = 0;
score = 0;
[self createEditableCopyOfDatabaseIfNeeded];
sqlite3 *dbc = [quiz getNewDBConnection];
sqlite3_stmt *statement = nil;
const char *sqlSelect = "select * from QnA ORDER BY RANDOM()";
if(sqlite3_prepare_v2(dbc, sqlSelect, -1, &statement, NULL)!=SQLITE_OK)
{
NSAssert1(0, #"Error Preparing Statement", sqlite3_errmsg(dbc));
}
else
{
myarray = [[NSMutableArray alloc]init];
while(sqlite3_step(statement)==SQLITE_ROW)
{
NSString *q = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)];
NSString *o = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 1)];
NSString *a = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 2)];
DbVals *dbValsObj = [[DbVals alloc]init];
[dbValsObj setValsOfQuestions:q options:o answer:a];
[myarray addObject:dbValsObj];
[dbValsObj release];
}
}
sqlite3_finalize(statement);
//[self populate:questionNumber];
}
-(void)populate:(int)number
{
/*[scoreLabel_ setText:[NSString stringWithFormat:#"%d",score]];
AppDelegate *appDel = [[UIApplication sharedApplication] delegate];
[appDel setFinalScore:[NSString stringWithFormat:#"%d",score]];
if(number < [myarray count])
{
DbVals *dbv1 = [myarray objectAtIndex:number];
[questionTextView_ setText:[dbv1 getQuestions]];
NSString *joinedOptions = [dbv1 getOptions];
NSArray *splitOptions = [joinedOptions componentsSeparatedByString:#","];
[optionAButton_ setTitle:[splitOptions objectAtIndex:0] forState:UIControlStateNormal];
[optionBButton_ setTitle:[splitOptions objectAtIndex:1] forState:UIControlStateNormal];
[optionCButton_ setTitle:[splitOptions objectAtIndex:2] forState:UIControlStateNormal];
correctAnswer = [dbv1 getAnswer];
}
else
{
//viewTransition *vt = [[viewTransition alloc]init];
[viewTransition viewsTransitionCurrentView:self toNextView:#"result"];
//[vt release];
}*/
}
- (void)viewDidUnload
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"<u><u><u><u><><><><><><><><><><><>");
}
[self setQuestionTextView:nil];
[questionTextView_ release];
questionTextView_ = nil;
[self setQuestionTextView:nil];
[skipButton_ release];
skipButton_ = nil;
[self setSkipButton:nil];
[optionAButton_ release];
optionAButton_ = nil;
[self setOptionAButton:nil];
[optionBButton_ release];
optionBButton_ = nil;
[self setOptionBButton:nil];
[optionCButton_ release];
optionCButton_ = nil;
[self setOptionCButton:nil];
[scoreLabel_ release];
scoreLabel_ = nil;
[self setScoreLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"<d><d><d><d><d><><><><><><><><><><>");
}
[questionTextView_ release];
[skipButton_ release];
[optionAButton_ release];
[optionBButton_ release];
[optionCButton_ release];
[scoreLabel_ release];
[myarray release];
[super dealloc];
}
- (IBAction)optionsToAnswer:(id)sender
{
for(int i=0; i<[myarray count]; i++)
{
DbVals *dbv1 = [myarray objectAtIndex:i];
NSLog(#"%#",[dbv1 getQuestions]);
NSLog(#"%#",[dbv1 getOptions]);
NSLog(#"%#",[dbv1 getAnswer]);
NSLog(#"six");
}
if(sender == skipButton_)
{
//questionNumber++;
//[self populate:questionNumber];
/*[UIView animateWithDuration:5 delay:0 options: UIViewAnimationCurveEaseOut
animations:
^{
[UIView setAnimationTransition:103 forView:self.view cache:NO];
}
completion:
^(BOOL finished)
{
}
];*/
}
if(sender == optionAButton_)
{
/*NSString *one = #"1";
if([correctAnswer isEqualToString:one])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
if(sender == optionBButton_)
{
/*NSString *two = #"2";
if([correctAnswer isEqualToString:two])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
if(sender == optionCButton_)
{
/*NSString *three = #"3";
if([correctAnswer isEqualToString:three])
{
score++;
}
questionNumber++;
[self populate:questionNumber];*/
}
}
- (IBAction)zzz:(id)sender
{
}
#end
dbVals.h
#import <Foundation/Foundation.h>
#interface DbVals : NSObject
{
NSString *questions_;
NSString *options_;
NSString *answer_;
// NSString *hint;
// NSString *mode;
}
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer;
-(NSString*)getQuestions;
-(NSString*)getOptions;
-(NSString*)getAnswer;
dbVals.m
#import "DbVals.h"
#implementation DbVals
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer
{
questions_ = questions;
options_ = options;
answer_ = answer;
}
-(NSString*)getQuestions
{
return questions_;
}
-(NSString*)getOptions
{
return options_;
}
-(NSString*)getAnswer
{
return answer_;
}
#end
Your dbVals.m setVals isn't retaining the parameters. This obviously means, everything inside becomes deallocated once the function scope ends.
Try changing it to something like
-(void)setValsOfQuestions:(NSString*)questions options:(NSString*)options answer:(NSString*)answer
{
[questions_ release];
[options_ release];
[answer_ release];
questions_ = [questions copy];
options_ = [options copy];
answer_ = [answer copy];
}