Infinite loop traversing cloud storage file structure [Box api] - ios

I'm trying to get the metadata from the box api and so I need to traverse the entire directory structure. Here is the code:
- (IBAction)ls {
// INITIALIZE folderID (will be nil only for the root folder)
if (self.folderID == nil)
{
self.folderID = BoxAPIFolderIDRoot;
self.folderName = #"Root";
}
// START TRAVERSING DIRECTORY TREE
[self traverseItemsWithFolderID:self.folderID name:self.folderName];
}
- (void)traverseItemsWithFolderID:(NSString *)folder name:(NSString *)namefolder
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self fetchFolderItemsWithFolderID:folder name:namefolder]; // <- List Files/dirs in directory namefolder
dispatch_async(dispatch_get_main_queue(), ^{
// Create box object "item" to traverse folderItemsArray
BoxItem * item = (BoxItem *)[self.folderItemsArray objectEnumerator];
for (item in self.folderItemsArray)
{
if([item.type isEqualToString:BoxAPIItemTypeFolder])
{
NSLog(#"SubFolder id %#", item.modelID);
NSLog(#"SubFolder name %#", item.name);
[self traverseItemsWithFolderID:item.modelID name:item.name];
}
}
});
});
}
and this last method:
- (void)fetchFolderItemsWithFolderID:(NSString *)innerFolder name:(NSString *)innerFolderName
{
BoxFoldersResourceManager *mgr = [BoxSDK sharedSDK].foldersManager;
BoxFoldersRequestBuilder *bldr = [[BoxFoldersRequestBuilder alloc] initWithQueryStringParameters:#{ #"fields" : #"name,type,id,etag,size,modified_at,hash" }];
[mgr folderItemsWithID:innerFolder requestBuilder:bldr success: ^(BoxCollection *collection)
{
self.folderItemsArray = [NSMutableArray array];
for (NSUInteger i = 0; i < collection.numberOfEntries; i++)
{
[self.folderItemsArray addObject:[collection modelAtIndex:i]];
NSLog(#"FOLDER NAME %#", innerFolderName);
BoxItem *item = (BoxItem *)[self.folderItemsArray objectAtIndex:i];
NSLog(#"Here The list of Files/Directories:");
NSLog(#"TypE %#", item.type); // [file/directory]
NSLog(#"NAME %#", item.name); // filename
NSLog(#"ID %#", item.ETag); // directory level [0 = root]
NSLog(#"ID %#", item.modelID); // metadata unique identifier [FolderID !]
NSLog(#"SIZE %#", item.size); // in bytes
NSLog(#"Modified Time %#", item.modifiedAt); // in UTC format
NSLog(#"HASH %lu", (unsigned long)item.hash); // hash
}
self.totalCount = [collection.totalCount integerValue];
NSLog(#" Number of files/dirs in Level %ld", (long)self.totalCount);
}
The final result is that the code start an infinite loop of requests and don't understand why, as it should stop when there are no more directories. Any help on identifying the issue is much appreciated.
Thanks !

You should avoid using the property self.folderItemsArray since you have a recursive method, try this:
- (NSArray*)fetchFolderItemsWithFolderID:(NSString *)innerFolder name:(NSString *)innerFolderName
{
...
// This is a new line.
NSMutableArray* folderItemsArray = [NSMutableArray array];
[mgr folderItemsWithID:innerFolder requestBuilder:bldr success: ^(BoxCollection *collection)
{
//self.folderItemsArray = [NSMutableArray array]; remove this line.
for (NSUInteger i = 0; i < collection.numberOfEntries; i++)
{
[folderItemsArray addObject:[collection modelAtIndex:i]]; // remove the self here.
...
}
return folderItemsArray;
}
And update this method like this:
- (void)traverseItemsWithFolderID:(NSString *)folder name:(NSString *)namefolder
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray* items = [self fetchFolderItemsWithFolderID:folder name:namefolder]; // <- List Files/dirs in directory namefolder
dispatch_async(dispatch_get_main_queue(), ^{
// Create box object "item" to traverse folderItemsArray
//BoxItem * item = (BoxItem *)[self.folderItemsArray objectEnumerator]; why do you need this line.
for (BoxItem *item in items)
{
if([item.type isEqualToString:BoxAPIItemTypeFolder])
{
NSLog(#"SubFolder id %#", item.modelID);
NSLog(#"SubFolder name %#", item.name);
[self traverseItemsWithFolderID:item.modelID name:item.name];
}
}
});
});
}

Related

Is it possible to create a dispatch_async(dipatch_get_main_queue(), ^{}); with a completion go get when the dispatch block is finished?

I have a piece of code that execute a coredata update of the database, and I would like to know when that block is finished. Is there a way to get it knowing when the coredata has finished to update the tables?
Main function:
NSMutableArray* responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
dispatch_async(dispatch_get_main_queue(), ^{
[self parseAndAddLovAll:responseArray toArray:self.objects];
});
Function used in dispatch:
- (void)parseAndAddLovAll:(NSMutableArray*)responseArray toArray:(NSMutableArray*)destinationArray
{
NSError *error;
DB_ListOfValue_manage *elements_to_store = [[DB_ListOfValue_manage alloc] init];
NSManagedObjectContext * context = [elements_to_store managedObjectContext];
for (int index=0; index < [responseArray count]; index++)
{
NSDictionary * responseArray2 = [[NSDictionary alloc] initWithDictionary:responseArray[index]];
NSString * table_to_store = [[NSString alloc] initWithString:[responseArray2 objectForKey:#"table"]];
NSArray * lignes = [[NSArray alloc] initWithObjects:[responseArray2 objectForKey:#"lignes"], nil];
id value;
// Check if LOV table or contact table
if ((([#"Table_contact" compare:table_to_store])!=NSOrderedSame)&&
(([#"Table_event" compare:table_to_store])!=NSOrderedSame))
{
for (NSDictionary * item in lignes[0])
{
value = [item objectForKey:#"codeevent"];
if ([value isEqualToNumber:[NSNumber numberWithInt:EVENT_ID]])
{//FIXME: bug to check when SYNC
elements_to_store = (DB_ListOfValue_manage*)[NSEntityDescription insertNewObjectForEntityForName:table_to_store inManagedObjectContext:context];
elements_to_store.code_event = [value isKindOfClass:[NSNull class]] ? #"" : value;
value = [item objectForKey:#"id"];
elements_to_store.id = [value isKindOfClass:[NSNull class]] ? #"" : value;
value = [item objectForKey:#"used"];
elements_to_store.used = [value isKindOfClass:[NSNull class]] ? #"" : value;
if (![context save:&error]) {
#ifdef DEBUG
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
#endif
}
else{
#ifdef DEBUG
NSLog(#"Data saved to DB, table %# %# %#", table_to_store, elements_to_store.label1, elements_to_store.label2);
#endif
}
}
}
}
}
}

Realm+JSON: EXC BAD ACCESS when calling createOrUpdateInRealm:withJSONArray: second time

+ (NSDictionary *)mc_inboundMapping {
static NSMutableDictionary *mappingForClassName = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
mappingForClassName = [NSMutableDictionary dictionary];
});
#synchronized(mappingForClassName) {
NSDictionary *mapping = mappingForClassName[[self className]];//<----EXC BAD ACCESS here
if (!mapping) {
SEL selector = NSSelectorFromString(#"JSONInboundMappingDictionary");
if ([self respondsToSelector:selector]) {
mapping = MCValueFromInvocation(self, selector);
}
else {
mapping = [self mc_defaultInboundMapping];
}
mappingForClassName[[self className]] = mapping;
}
return mapping;
}
I'm using Realm+JSON with Realm. And got a problem with Realm+JSON.
When I attempt to call createOrUpdateInRealm:withJSONArray: multiple time in loop for multiple RLMObjects, the first RLMObject works OK, but the second RLMObject(no matter what class is) fails with EXC BAD ACCESS code1on static variable.
I think autorelease pool deallocate pointing NSMutableDictionary.Anybody got this issue? I'm using XCode 6.3.2 and Realm 0.96.3.
+ (NSArray *)createOrUpdateInRealm:(RLMRealm *)realm withJSONArray:(NSArray *)array {
NSInteger count = array.count;
NSMutableArray *result = [NSMutableArray array];
for (NSInteger index=0; index*kCreateBatchSize<count; index++) {
NSInteger size = MIN(kCreateBatchSize, count-index*kCreateBatchSize);
#autoreleasepool
{
for (NSInteger subIndex=0; subIndex<size; subIndex++) {
NSDictionary *dictionary = array[index*kCreateBatchSize+subIndex];
id object = [self createOrUpdateInRealm:realm withJSONDictionary:dictionary];
[result addObject:object];
}
}
}
return [result copy];
}
calling here...
[realm beginWriteTransaction];
if ([collection isKindOfClass:[NSDictionary class]])
{
for (NSString *key in [collection allKeys])
{
NSLog(#"Set Data == %#:%#", key, collection[key]);
id jsData = [collection[key] objectForKey:#"data"];
if ([key isEqualToString:STATIC_ERROR_MSGS])
{
[SErrorMsgs createOrUpdateInRealm:realm withJSONArray:jsData];
}
else if ([key isEqualToString:STATIC_EPISODE])
{
[SEpisode createOrUpdateInRealm:realm withJSONArray:jsData];
}
else if ([key isEqualToString:STATIC_INGAME_TUTORIAL])
{
[SIngameTutorial createOrUpdateInRealm:realm withJSONArray:jsData];
} //more cases.........edited

Memory Pressure Issue in read Metadata and remove duplicate

-(void) objectParsed_ListAllMedia:(NSDictionary *)dictionary
{
#try {
self.viewLoading.hidden=1;
[self.arrGaalleryMediaName removeAllObjects];
[self.arrMediaNames removeAllObjects];
if(self.arrOnlyServerImages == nil){
self.arrOnlyServerImages = [[NSMutableArray alloc] init];
}
if([self.arrOnlyServerImages count] >0){
[self.arrOnlyServerImages removeAllObjects];
}
if (dictionary==nil) {
[self.gridCollectionView reloadData];
return;
}
// Filter Array for Audio file
NSPredicate *predicate = [NSPredicate predicateWithFormat: #"type != 'audio' "];
self.arrOnlyServerImages = [NSMutableArray arrayWithArray:[[dictionary objectForKey:#"objects"] filteredArrayUsingPredicate:predicate]];
// Remove duplicate Start //Read Meta Data and Duplicate from Download, Duplicate from upload START
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.memreas.myqueue", 0);
dispatch_async(backgroundQueue, ^{
NSMutableArray *arr = [NSMutableArray array];
NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
for (int i=0; self.assetAry.count>i; i++) {
ALAsset *result =self.assetAry[i];
ALAssetRepresentation *imageRep = [result defaultRepresentation];
NSDictionary * customMetaDic = [imageRep metadata][(NSString*)kCGImagePropertyIPTCDictionary];
if (customMetaDic) {
[self.arrMediaNames addObject:customMetaDic[(NSString*)kCGImagePropertyIPTCObjectName]?customMetaDic[(NSString*)kCGImagePropertyIPTCObjectName]:#""];
}else{
[self.arrMediaNames addObject:#""];
}
[self.arrGaalleryMediaName addObject:[self getFileNameWithExtensionFromPath:imageRep.url]];
}
for (int i=0; self.arrOnlyServerImages.count>i; i++) {
NSMutableDictionary* obj = self.arrOnlyServerImages[i];
NSMutableDictionary * dic2 = [NSMutableDictionary dictionaryWithDictionary:obj];
BOOL isArrMedia =[self.arrMediaNames containsObject:dic2[#"media_name"]];
BOOL isGallery =[self.arrGaalleryMediaName containsObject:dic2[#"media_name"]];
if (isArrMedia||isGallery) {
dic2[#"isDownloaded"] = [NSNumber numberWithBool:YES];
[indexSet addIndex: isArrMedia?[self.arrMediaNames indexOfObject:dic2[#"media_name"]] :[self.arrGaalleryMediaName indexOfObject:dic2[#"media_name"]]];
}else{
dic2[#"isDownloaded"] = [NSNumber numberWithBool:NO];
}
[arr addObject:dic2];
}
dispatch_async(dispatch_get_main_queue(), ^{
#try {
self.arrOnlyServerImages = arr;
[self.assetAry removeObjectsAtIndexes:indexSet];
[self.gridCollectionView reloadData];
}
#catch (NSException *exception) {
NSLog(#"%#",exception);
[self.gridCollectionView reloadData];
}
});
});
// Remove duplicate END //Read Meta Data and Duplicate from Download, Duplicate from upload END
[self.gridCollectionView reloadData];
[self.gridView.collectionView reloadData];
[self.location performSelector:#selector(stopActivity) withObject:nil afterDelay:2];
}
#catch (NSException *exception) {
NSLog(#"%#",exception);
}
}
I have issue with my code, While I run this code it generates memory pressure issue and crash the app.
Functionality is:
I load all the images from server and local assets and match each other with file name and remove duplicate images from list, So it will visible only once.
Any one have solution so please help.
thanks in advance.
You're accessing memory-intensive things (ALAssetRepresentations) in a tight loop. In these cases a local autoreleasepool can help ARC to keep your memory use down.
Inside the loop where you pass through self.assetAry, wrap everything in an autoreleasepool like so:
#autoreleasepool {
AlAsset *asset = ...
...
// Rest of your code
}

Loading csv file in Core Data

I am trying to load a csv file in core data when the application is ran for the first time. On another post on stackoverflow found here (What is the fastest way to load a large CSV file into core data), I found out how to do that.
I am using the same code form the provided function: populateDB, in my controller and calling the function if the data has never been loaded before (first run). However, xcode is giving me an error:
No visible #interface for ...Controller declares the selector persistentStoreCoordinator.
The function is:
-(void)populateDB{
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
NSManagedObjectContext *context;
if (coordinator != nil) {
context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:coordinator];
}
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"input" ofType:#"txt"];
if (filePath) {
NSString * myText = [[NSString alloc]
initWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:nil];
if (myText) {
__block int count = 0;
[myText enumerateLinesUsingBlock:^(NSString * line, BOOL * stop) {
line=[line stringByReplacingOccurrencesOfString:#"\t" withString:#" "];
NSArray *lineComponents=[line componentsSeparatedByString:#" "];
if(lineComponents){
if([lineComponents count]==3){
float f=[[lineComponents objectAtIndex:0] floatValue];
NSNumber *number=[NSNumber numberWithFloat:f];
NSString *string1=[lineComponents objectAtIndex:1];
NSString *string2=[lineComponents objectAtIndex:2];
NSManagedObject *object=[NSEntityDescription insertNewObjectForEntityForName:#"Bigram" inManagedObjectContext:context];
[object setValue:number forKey:#"number"];
[object setValue:string1 forKey:#"string1"];
[object setValue:string2 forKey:#"string2"];
NSError *error;
count++;
if(count>=1000){
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
count=0;
}
}
}
}];
NSLog(#"done importing");
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
}
}
I am picking up iOS again after 3 years of absence and I have never dived into this part of the SDK before. I would greatly appreciate any help with this issue...
The code below shows you an example to load csv file in Core Data using the class CSVParser.hof Matt Gallagher and supposing an entity MyEntity
// CSV File input.csv and not input.txt separate by space #" "
CSVParser *csvParser = [[CSVParser alloc] initWithContentOfFile:[NSBundle mainBundle] pathForResource:#"input" ofType:#"csv" separator:#" "];
// Array with all your data from CSV
NSArray *data = [csvParser parseFile];
// Your entity from Core Data
MyEntity *myEntity = nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
for (NSDictionary *dic in data)
{
fetchRequest.entity = [NSEntityDescription entityForName:#"MyEntity" inManagedObjectContext:context];
if (!entity)
entity = [NSEntityDescription insertNewObjectForEntityForName:#"MyEntity"
inManagedObjectContext:context];
[entity setValue:number forKey:#"number"];
[entity setValue:string1 forKey:#"string1"];
[entity setValue:string2 forKey:#"string2"];
}
// Save the context
[managedObjectContext save:nil];
CVSParser.h using ARC :
//
// CSVParser.h
// CSVImporter
//
// Created by Matt Gallagher on 2009/11/30.
// Copyright 2009 Matt Gallagher. All rights reserved.
//
// Permission is given to use this source code file, free of charge, in any
// project, commercial or otherwise, entirely at your risk, with the condition
// that any redistribution (in part or whole) of source code must retain
// this copyright and permission notice. Attribution in compiled projects is
// appreciated but not required.
//
// Source : http://cocoawithlove.com/2009/11/writing-parser-using-nsscanner-csv.html
#interface CSVParser : NSObject
{
NSString *csvString;
NSString *separator;
NSScanner *scanner;
BOOL hasHeader;
NSMutableArray *fieldNames;
id receiver;
SEL receiverSelector;
NSCharacterSet *endTextCharacterSet;
BOOL separatorIsSingleChar;
}
- (id)initWithString:(NSString *)aCSVString
separator:(NSString *)aSeparatorString;
- (id)initWithContentOfFile:(NSString *)aPath
separator:(NSString *)aSeparatorString;
- (id)initWithString:(NSString *)aCSVString
separator:(NSString *)aSeparatorString
hasHeader:(BOOL)header
fieldNames:(NSArray *)names;
- (id)initWithContentOfFile:(NSString *)aPath
separator:(NSString *)aSeparatorString
hasHeader:(BOOL)header
fieldNames:(NSArray *)names;
- (NSArray *)arrayOfParsedRows;
- (void)parseRowsForReceiver:(id)aReceiver selector:(SEL)aSelector;
- (NSArray *)parseFile;
- (NSMutableArray *)parseHeader;
- (NSDictionary *)parseRecord;
- (NSString *)parseName;
- (NSString *)parseField;
- (NSString *)parseEscaped;
- (NSString *)parseNonEscaped;
- (NSString *)parseDoubleQuote;
- (NSString *)parseSeparator;
- (NSString *)parseLineSeparator;
- (NSString *)parseTwoDoubleQuotes;
- (NSString *)parseTextData;
#end
CVSParser.m using ARC :
//
// CSVParser.m
// CSVImporter
//
// Created by Matt Gallagher on 2009/11/30.
// Copyright 2009 Matt Gallagher. All rights reserved.
//
// Permission is given to use this source code file, free of charge, in any
// project, commercial or otherwise, entirely at your risk, with the condition
// that any redistribution (in part or whole) of source code must retain
// this copyright and permission notice. Attribution in compiled projects is
// appreciated but not required.
//
#import "CSVParser.h"
#implementation CSVParser
//
// initWithString:separator:hasHeader:fieldNames:
//
// Parameters:
// aCSVString - the string that will be parsed
// aSeparatorString - the separator (normally "," or "\t")
// header - if YES, treats the first row as a list of field names
// names - a list of field names (will have no effect if header is YES)
//
// returns the initialized object (nil on failure)
//
- (id)initWithString:(NSString *)aCSVString
separator:(NSString *)aSeparatorString
hasHeader:(BOOL)header
fieldNames:(NSArray *)names
{
self = [super init];
if (self)
{
csvString = [aCSVString retain];
separator = [aSeparatorString retain];
NSAssert([separator length] > 0 &&
[separator rangeOfString:#"\""].location == NSNotFound &&
[separator rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location == NSNotFound,
#"CSV separator string must not be empty and must not contain the double quote character or newline characters.");
NSMutableCharacterSet *endTextMutableCharacterSet =
[[NSCharacterSet newlineCharacterSet] mutableCopy];
[endTextMutableCharacterSet addCharactersInString:#"\""];
[endTextMutableCharacterSet addCharactersInString:[separator substringToIndex:1]];
endTextCharacterSet = endTextMutableCharacterSet;
if ([separator length] == 1)
{
separatorIsSingleChar = YES;
}
hasHeader = header;
fieldNames = [names mutableCopy];
}
return self;
}
- (id)initWithString:(NSString *)aCSVString
separator:(NSString *)aSeparatorString
{
return [self initWithString:aCSVString
separator:aSeparatorString
hasHeader:YES
fieldNames:nil];
}
- (id)initWithContentOfFile:(NSString *)aPath
separator:(NSString *)aSeparatorString
{
return [self initWithString:[NSString stringWithContentsOfFile:aPath
encoding:NSUTF8StringEncoding
error:nil]
separator:aSeparatorString];
}
- (id)initWithContentOfFile:(NSString *)aPath
separator:(NSString *)aSeparatorString
hasHeader:(BOOL)header
fieldNames:(NSArray *)names
{
return [self initWithString:[NSString stringWithContentsOfFile:aPath
encoding:NSUTF8StringEncoding
error:nil]
separator:aSeparatorString
hasHeader:header
fieldNames:names];
}
//
// dealloc
//
// Releases instance memory.
//
- (void)dealloc
{
[csvString release];
[separator release];
[fieldNames release];
[endTextCharacterSet release];
[super dealloc];
}
//
// arrayOfParsedRows
//
// Performs a parsing of the csvString, returning the entire result.
//
// returns the array of all parsed row records
//
- (NSArray *)arrayOfParsedRows
{
scanner = [[NSScanner alloc] initWithString:csvString];
[scanner setCharactersToBeSkipped:[[[NSCharacterSet alloc] init] autorelease]];
NSArray *result = [self parseFile];
[scanner release];
scanner = nil;
return result;
}
//
// parseRowsForReceiver:selector:
//
// Performs a parsing of the csvString, sending the entries, 1 row at a time,
// to the receiver.
//
// Parameters:
// aReceiver - the target that will receive each row as it is parsed
// aSelector - the selector that will receive each row as it is parsed
// (should be a method that takes a single NSDictionary argument)
//
- (void)parseRowsForReceiver:(id)aReceiver selector:(SEL)aSelector
{
scanner = [[NSScanner alloc] initWithString:csvString];
[scanner setCharactersToBeSkipped:[[[NSCharacterSet alloc] init] autorelease]];
receiver = [aReceiver retain];
receiverSelector = aSelector;
[self parseFile];
[scanner release];
scanner = nil;
[receiver release];
receiver = nil;
}
//
// parseFile
//
// Attempts to parse a file from the current scan location.
//
// returns the parsed results if successful and receiver is nil, otherwise
// returns nil when done or on failure.
//
- (NSArray *)parseFile
{
scanner = [[NSScanner alloc] initWithString:csvString];
[scanner setCharactersToBeSkipped:[[[NSCharacterSet alloc] init] autorelease]];
if (hasHeader)
{
if (fieldNames)
{
[fieldNames release];
}
fieldNames = [[self parseHeader] retain];
if (!fieldNames || ![self parseLineSeparator])
{
return nil;
}
}
NSMutableArray *records = nil;
if (!receiver)
{
records = [NSMutableArray array];
}
NSDictionary *record = [[self parseRecord] retain];
if (!record)
{
return nil;
}
while (record)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (receiver)
{
[receiver performSelector:receiverSelector withObject:record];
}
else
{
[records addObject:record];
}
[record release];
if (![self parseLineSeparator])
{
break;
}
record = [[self parseRecord] retain];
[pool drain];
}
[scanner release];
scanner = nil;
return records;
}
//
// parseHeader
//
// Attempts to parse a header row from the current scan location.
//
// returns the array of parsed field names or nil on parse failure.
//
- (NSMutableArray *)parseHeader
{
NSString *name = [self parseName];
if (!name)
{
return nil;
}
NSMutableArray *names = [NSMutableArray array];
while (name)
{
[names addObject:name];
if (![self parseSeparator])
{
break;
}
name = [self parseName];
}
return names;
}
//
// parseRecord
//
// Attempts to parse a record from the current scan location. The record
// dictionary will use the fieldNames as keys, or FIELD_X for each column
// X-1 if no fieldName exists for a given column.
//
// returns the parsed record as a dictionary, or nil on failure.
//
- (NSDictionary *)parseRecord
{
//
// Special case: return nil if the line is blank. Without this special case,
// it would parse as a single blank field.
//
if ([self parseLineSeparator] || [scanner isAtEnd])
{
return nil;
}
NSString *field = [self parseField];
if (!field)
{
return nil;
}
NSInteger fieldNamesCount = [fieldNames count];
NSInteger fieldCount = 0;
NSMutableDictionary *record =
[NSMutableDictionary dictionaryWithCapacity:[fieldNames count]];
while (field)
{
NSString *fieldName;
if (fieldNamesCount > fieldCount)
{
fieldName = [fieldNames objectAtIndex:fieldCount];
}
else
{
fieldName = [NSString stringWithFormat:#"FIELD_%d", fieldCount + 1];
[fieldNames addObject:fieldName];
fieldNamesCount++;
}
[record setObject:field forKey:fieldName];
fieldCount++;
if (![self parseSeparator])
{
break;
}
field = [self parseField];
}
return record;
}
//
// parseName
//
// Attempts to parse a name from the current scan location.
//
// returns the name or nil.
//
- (NSString *)parseName
{
return [self parseField];
}
//
// parseField
//
// Attempts to parse a field from the current scan location.
//
// returns the field or nil
//
- (NSString *)parseField
{
NSString *escapedString = [self parseEscaped];
if (escapedString)
{
return escapedString;
}
NSString *nonEscapedString = [self parseNonEscaped];
if (nonEscapedString)
{
return nonEscapedString;
}
//
// Special case: if the current location is immediately
// followed by a separator, then the field is a valid, empty string.
//
NSInteger currentLocation = [scanner scanLocation];
if ([self parseSeparator] || [self parseLineSeparator] || [scanner isAtEnd])
{
[scanner setScanLocation:currentLocation];
return #"";
}
return nil;
}
//
// parseEscaped
//
// Attempts to parse an escaped field value from the current scan location.
//
// returns the field value or nil.
//
- (NSString *)parseEscaped
{
if (![self parseDoubleQuote])
{
return nil;
}
NSString *accumulatedData = [NSString string];
while (YES)
{
NSString *fragment = [self parseTextData];
if (!fragment)
{
fragment = [self parseSeparator];
if (!fragment)
{
fragment = [self parseLineSeparator];
if (!fragment)
{
if ([self parseTwoDoubleQuotes])
{
fragment = #"\"";
}
else
{
break;
}
}
}
}
accumulatedData = [accumulatedData stringByAppendingString:fragment];
}
if (![self parseDoubleQuote])
{
return nil;
}
return accumulatedData;
}
//
// parseNonEscaped
//
// Attempts to parse a non-escaped field value from the current scan location.
//
// returns the field value or nil.
//
- (NSString *)parseNonEscaped
{
return [self parseTextData];
}
//
// parseTwoDoubleQuotes
//
// Attempts to parse two double quotes from the current scan location.
//
// returns a string containing two double quotes or nil.
//
- (NSString *)parseTwoDoubleQuotes
{
if ([scanner scanString:#"\"\"" intoString:NULL])
{
return #"\"\"";
}
return nil;
}
//
// parseDoubleQuote
//
// Attempts to parse a double quote from the current scan location.
//
// returns #"\"" or nil.
//
- (NSString *)parseDoubleQuote
{
if ([scanner scanString:#"\"" intoString:NULL])
{
return #"\"";
}
return nil;
}
//
// parseSeparator
//
// Attempts to parse the separator string from the current scan location.
//
// returns the separator string or nil.
//
- (NSString *)parseSeparator
{
if ([scanner scanString:separator intoString:NULL])
{
return separator;
}
return nil;
}
//
// parseLineSeparator
//
// Attempts to parse newline characters from the current scan location.
//
// returns a string containing one or more newline characters or nil.
//
- (NSString *)parseLineSeparator
{
NSString *matchedNewlines = nil;
[scanner
scanCharactersFromSet:[NSCharacterSet newlineCharacterSet]
intoString:&matchedNewlines];
return matchedNewlines;
}
//
// parseTextData
//
// Attempts to parse text data from the current scan location.
//
// returns a non-zero length string or nil.
//
- (NSString *)parseTextData
{
NSString *accumulatedData = [NSString string];
while (YES)
{
NSString *fragment;
if ([scanner scanUpToCharactersFromSet:endTextCharacterSet intoString:&fragment])
{
accumulatedData = [accumulatedData stringByAppendingString:fragment];
}
//
// If the separator is just a single character (common case) then
// we know we've reached the end of parseable text
//
if (separatorIsSingleChar)
{
break;
}
//
// Otherwise, we need to consider the case where the first character
// of the separator is matched but we don't have the full separator.
//
NSUInteger location = [scanner scanLocation];
NSString *firstCharOfSeparator;
if ([scanner scanString:[separator substringToIndex:1] intoString:&firstCharOfSeparator])
{
if ([scanner scanString:[separator substringFromIndex:1] intoString:NULL])
{
[scanner setScanLocation:location];
break;
}
//
// We have the first char of the separator but not the whole
// separator, so just append the char and continue
//
accumulatedData = [accumulatedData stringByAppendingString:firstCharOfSeparator];
continue;
}
else
{
break;
}
}
if ([accumulatedData length] > 0)
{
return accumulatedData;
}
return nil;
}
#end
Thanks for everyone's assistance. I found the answer on stackoverflow, a 2-3 years old forum (Adding Core Data to existing iPhone project)...
So the issue it seems is that when I first created the project I didn't request using core data and only did that later on. Following the post I posted above:
Add the following to supporting files/projectName-Prefix.pch
#import <CoreData/CoreData.h>
Once I did, the persistenceCoordinator error disappeared...
WOW, big lesson learned there...
-(void)populateDB {
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
NSManagedObjectContext *context;
[....]
}
The Problem might be [self persistentStoreCoordinator]... Do you have a function called "persistentStoreCoordinator" ? If not, you have to write the function.
[EDIT]
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
#synchronized (self)
{
if (__persistentStoreCoordinator != nil)
return __persistentStoreCoordinator;
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:#"myProject" ofType:#"sqlite"];
NSString *storePath = [[[self applicationDocumentsDirectory] path] stringByAppendingPathComponent: #"myProject.sqlite"];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:storePath])
{
if ([[NSFileManager defaultManager] copyItemAtPath:defaultStorePath toPath:storePath error:&error])
NSLog(#"Copied starting data to %#", storePath);
else
NSLog(#"Error copying default DB to %# (%#)", storePath, error);
}
NSURL *storeURL = [NSURL fileURLWithPath:storePath];
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
}
Is this Code in another File ? Maybe you forgot to import the .h-file, where persistentStoreCoordinator is declared in.

Why mi property do not save the value when I use SudzC?

I am using SudzC to get webservices, that webservice give me data, I tried to save the data in a property, but when I use to fill a tableview the property don't have any data. I use the debugger to view the property.
This es my handler
- (void) ConsultarUnidadesOrganizacionalesPorEmpresaHandler: (id) value {
// Handle errors
if([value isKindOfClass:[NSError class]]) {
NSLog(#"%#", value);
return;
}
// Handle faults
if([value isKindOfClass:[SoapFault class]]) {
NSLog(#"%#", value);
return;
}
// Do something with the NSMutableArray* result
NSMutableArray *result = (NSMutableArray*)value;
NSMutableArray *unidadOrganizacional = [[NSMutableArray alloc] init];
self.myData = [NSMutableArray array];
for (int i = 0; i < [result count]; i++)
{
EWSUnidadNegocio *empresa = [[EWSUnidadNegocio alloc] init];
empresa = [result objectAtIndex:i];
[unidadOrganizacional addObject:[empresa Descripcion]];
}
self.myData = unidadOrganizacional;
}
And this is the part where I use the web service
- (void)viewDidLoad
{
// Do any additional setup after loading the view from its nib.
EWSEmpresaWebServiceSvc *service = [[EWSEmpresaWebServiceSvc alloc]init];
[service ConsultarUnidadesOrganizacionalesPorEmpresa:self action:#selector(ConsultarUnidadesOrganizacionalesPorEmpresaHandler:) EmpresaId:self.empresaID];
[super viewDidLoad];
}
And the tableview is empty. Why does this happen? How can I use the data and fill my tableview?
Try to change your code this way :
self.myData = [[NSMutableArray alloc] init]autorelease];
// your loop
[sel setMyData:unidadOrganizacional];
try loading it in a dictionary:
dict = [resp objectForKey:#"YourKey"];
if( ( dict == nil ) || ![dict isKindOfClass:[NSDictionary class]] ) {
NSLog( #"WARNING: %#", [dict description]);
return;
}
empID = [[dict objectForKey:#"empresaID"]copy];
NSLog(#"Your Value: %#", empID);
I found the answer, I just have to put
[_myTableView reloadData]
at the end of the method.

Resources