Search Results

Search found 1009 results on 41 pages for 'nsarray'.

Page 7/41 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • should variable be released or not? iphone-sdk

    - by psebos
    Hi, In the following piece of code (from a book) data is an NSDictionary *data; defined in the header (no property). In the viewDidLoad of the controller the following occurs: - (void)viewDidLoad { [super viewDidLoad]; NSArray *keys = [NSArray arrayWithObjects:@"home", @"work", nil]; NSArray *homeDVDs = [NSArray arrayWithObjects:@"Thomas the Builder", nil]; NSArray *workDVDs = [NSArray arrayWithObjects:@"Intro to Blender", nil]; NSArray *values = [NSArray arrayWithObjects:homeDVDs, workDVDs, nil]; data = [[NSDictionary alloc] initWithObjects:values forKeys:keys]; } Since I am really new to objective-c can someone explain to me why I do not have to retain the variables keys,homeDVDs,workDVDs and values prior exiting the function? I would expect prior the data allocation something like: [keys retain]; [homeDVDs retain]; [workDVDs retain]; [values retain]; or not? Does InitWithObjects copies (recursively) all objects into a new table? Assuming we did not have the last line (data allocation) should we release all the NSArrays prior exiting the function (or we could safely assumed that all NSArrays will be autoreleased since there is no alloc for each one?) Thanks!!!!

    Read the article

  • Memory management technique for Objective-C iVars/properties

    - by David Rea
    Is the following code doing anything unnecessary? @interface MyClass { NSArray *myArray; } -(void)replaceArray:(NSArray *)newArray; @implementation MyClass -(void)replaceArray:(NSArray *)newArray { if( myArray ) { [myArray release]; myArray = nil; } myArray = [[NSArray alloc] initWithArray: newArray]; } @end What if I made the following changes: 1) Made myArray a property: @property (nonatomic, retain) NSArray myArray; 2) Changed the assignment to: self.myArray = [NSArray arrayWithArray: newArray]; Would that allow me to remove the conditional?

    Read the article

  • Looping through NSArray while subtracting values from each object? [on hold]

    - by Julian
    I have NSNumber objects stored in an NSMutableArray. I am attempting to perform a calculation on each object in the array. What I want to do is: 1) Take a random higher number variable and keep subtracting a smaller number variable in increments until the value of the variable is equal to the value in the array. For example: NSMutableArray object is equal to 2.50. I have an outside variable of 25 that is not in the array. I want to subtract 0.25 multiple times from the variable until I reach less than or equal to 2.50. I also need a parameter so if the number does not divide evenly and goes below the array value, it resorts to the original array value of 2.50. Lastly, for each iteration, I want to print the values as they are counting down as a string. I was going to provide code, but I don't want to make this more confusing than it has to be. So my output would be: VALUE IS: 24.75 VALUE IS: 24.50 VALUE IS: 24.25 … VALUE IS: 2.50 END

    Read the article

  • Singleton EXC_BAD_ACCESS

    - by lclaud
    Hi, so I have a class that I decleare as a singleton and in that class I have a NSMutableArray that contains some NSDictionaries with some key/value pairs in them. The trouble is it doesn't work and I dont't know why... I mean it crashes with EXC_BAD_ACCESS but i don't know where. I followed the code and it did create a new array on first add, made it to the end of the funtion ..and crashed ... @interface dataBase : NSObject { NSMutableArray *inregistrari; } @property (nonatomic,retain) NSMutableArray *inregistrari; -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu; -(NSDictionary *)raportIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)luniDisponibileIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)aniDisponibiliIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)vectorDateIntreData:(NSDate *)dataI siData:(NSDate *)dataF; -(void)salveazaInFisier; -(void)incarcaDinFisier; + (dataBase *)shareddataBase; @end And here is the .m file #import "dataBase.h" #import "SynthesizeSingleton.h" @implementation dataBase @synthesize inregistrari; SYNTHESIZE_SINGLETON_FOR_CLASS(dataBase); -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu{ NSNumber *v=[NSNumber numberWithBool:venit]; NSArray *input=[NSArray arrayWithObjects:data,suma,v,detaliu,nil]; NSArray *keys=[NSArray arrayWithObjects:@"data",@"suma",@"venit",@"detaliu",nil]; NSDictionary *inreg=[NSDictionary dictionaryWithObjects:input forKeys:keys]; if(inregistrari == nil) { inregistrari=[[NSMutableArray alloc ] initWithObjects:inreg,nil]; }else { [inregistrari addObject:inreg]; } [inreg release]; [input release]; [keys release]; } It made it to the end of that adaugaInregistrareCuData ... ok . said the array had one object ... and then crashed

    Read the article

  • sigleton EXC_BAD_ACCESS

    - by lclaud
    Hi, so I have a class that I decleare as a singleton and in that class I have a NSMutableArray that contains some NSDictionaries with some key/value pairs in them. The trouble is it doesn't work and I dont't know why... I mean it crashes with EXC_BAD_ACCESS but i don't know where. I followed the code and it did create a new array on first add, made it to the end of the funtion ..and crashed ... @interface dataBase : NSObject { NSMutableArray *inregistrari; } @property (nonatomic,retain) NSMutableArray *inregistrari; -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu; -(NSDictionary *)raportIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)luniDisponibileIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)aniDisponibiliIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)vectorDateIntreData:(NSDate *)dataI siData:(NSDate *)dataF; -(void)salveazaInFisier; -(void)incarcaDinFisier; + (dataBase *)shareddataBase; @end And here is the .m file #import "dataBase.h" #import "SynthesizeSingleton.h" @implementation dataBase @synthesize inregistrari; SYNTHESIZE_SINGLETON_FOR_CLASS(dataBase); -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu{ NSNumber *v=[NSNumber numberWithBool:venit]; NSArray *input=[NSArray arrayWithObjects:data,suma,v,detaliu,nil]; NSArray *keys=[NSArray arrayWithObjects:@"data",@"suma",@"venit",@"detaliu",nil]; NSDictionary *inreg=[NSDictionary dictionaryWithObjects:input forKeys:keys]; if(inregistrari == nil) { inregistrari=[[NSMutableArray alloc ] initWithObjects:inreg,nil]; }else { [inregistrari addObject:inreg]; } [inreg release]; [input release]; [keys release]; } It made it to the end of that adaugaInregistrareCuData ... ok . said the array had one object ... and then crashed

    Read the article

  • Retrieving Relationships from within two arrays of pointers

    - by DanF
    In a portion of a program I'm working on, I need to count all the times each person has worked on projects with each other person. Let's say we have "Employee" entities and "Session" entities. In each session, there are four project types, "A", "B", "C", & "D", each a many-to-many relationship to Employees. I'm making a loop to systematically review every person a selected person has worked with. First, I put all their project types in a single array, so it's easier to loop through, but by the time I ask the last nested Project for its Employee members, I get an "unrecognized selector" error. IBOutlet NSArrayController * list; int x; for(x = 0; x < [list count]; x++){ NSArray *A = [[list objectAtIndex:x] valueForKey:@"projectAs"]; NSArray *A = [[list objectAtIndex:x] valueForKey:@"projectBs"]; NSArray *A = [[list objectAtIndex:x] valueForKey:@"projectCs"]; NSArray *A = [[list objectAtIndex:x] valueForKey:@"projectDs"]; NSArray *masterList = [[NSArray alloc] initWithObjects: projectAs, projectBs, projectCs, projectDs, nil]; int y; for(y = 0; y < [masterList count]; y++){ int z; for(z = 0; z < [[masterlist objectAtIndex:y] count]; z++){ //And now to make an Array of this employee's partners on the selected object, to run comparisons on. //I also have an array of keys for each session's teams, so that's what I'm referencing here: NSArray * thisTeam = [list objectAtIndex:y] objectAtIndex:z] valueForKey:projectKey]; This throws an exception... namely, -[_NSFaultingMutableSet objectAtIndex:]: unrecognized selector sent to instance What's wrong with that last Array creation?

    Read the article

  • Integers not properly returned from a property list (plist) array in Objective-C

    - by Gaurav
    In summary, I am having a problem where I read what I expect to be an NSNumber from an NSArray contained in a property list and instead of getting a number such as '1', I get what looks to be a memory address (i.e. '61879840'). The numbers are clearly correct in the property list. Below is my process for creating the property list and reading it back. Creating the property list I have created a simple Objective-C property list with arrays of integers within one root array: <array> <array> <integer>1</integer> <integer>2</integer> </array> <array> <integer>1</integer> <integer>2</integer> <integer>5</integer> </array> ... more arrays with integers ... </array> The arrays are NSArray objects and the integers are NSNumber objects. The property list has been created and serialized using the following code: // factorArray is an NSArray that contains NSArrays of NSNumbers as described above // serialize and compress factorArray as a property list, Factors-bin.plist NSString *error; NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [rootPath stringByAppendingPathComponent:@"Factors-bin.plist"]; NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:factorArray format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]; Inspecting the created plist, all values and types are correct. Reading the property list The property list is read in as Data and then converted to an NSArray: NSString *path = [[NSBundle mainBundle] pathForResource:@"Factors" ofType:@"plist"]; NSData *plistData = [[NSData alloc] initWithContentsOfFile:path]; NSPropertyListFormat format; NSString *error = nil; NSArray *factorData = (NSArray *)[NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error]; Cycling through factorData to see what it contains is where I see the erroneous integers: for (int i = 0; i < 10; i++) { NSArray *factorList = (NSArray *)[factorData objectAtIndex:i]; NSLog(@"Factors of %d\n", i + 1); for (int j = 0; j < [factorList count]; j++) { NSLog(@" %d\n", (NSNumber *)[factorList objectAtIndex:j]); } } I see all the correct number of values, but the values themselves are incorrect, i.e.: Factors of 3 61879840 (should be 1) 61961200 (should be 3) Factors of 4 61879840 (should be 1) 61943472 (should be 2) 61943632 (should be 4) Factors of 5 61879840 (should be 1) 61943616 (should be 5)

    Read the article

  • How do I remove a button from a view controller's toolbar on the iPhone?

    - by Tony
    I have code that works great for adding a button to the toolbar: NSArray* toolbarItems = [NSArray arrayWithObjects:flexibleSpace,shuffleBarItem,flexibleSpace,nil]; self.toolbarItems = toolbarItems; However, I also want to be able to remove toolbar items. When I use the below method, my application crashes: NSArray* toolbarItems = [NSArray arrayWithObjects:flexibleSpace,nil]; self.toolbarItems = toolbarItems; Does anyone know how I can dynamically alter the toolbar on the iPhone? Thanks!

    Read the article

  • How do I declare an array as a constant in Objective-c?

    - by Andrew
    The following code is giving me errors: // constants.h extern NSArray const *testArray; // constants.m NSArray const *testArray = [NSArray arrayWithObjects: @"foo", @"bar"]; The error I get is initializer element is not constant Or if I take away the pointer indicator (*) I get: statically allocated instance of Objective-C class 'NSArray'

    Read the article

  • Memory cleanup on returned array from static method (objective-c)

    - by Michael Bordelon
    In objective-c, I have a utility class with a bunch of static methods that I call for various tasks. As an example, I have one method that returns an NSArray that I allocate in the static method. If I set the NSArray to autorelease, then some time later, the NSArray in my calling method (that is assigned to the returned pointer) losses it's reference because the original form the static method is cleaned up. I can't release the NSArray object in the static method because it needs to be around for the return and assignment. What is the right way to return an object (like the NSArray) from a static class, and have it hang around for the calling class, but then get cleaned up later when it is no longer needed? Do I have to create the object first in the caller and pass in a pointer to the object and then return that same object form the static method? I know this is a basic O-O problem, I just never had this issue in Java and I do not do much C/C++. Thanks for your help.

    Read the article

  • How to simplify my code... 2D array in Objective C...?

    - by Tattat
    self.myArray = [NSArray arrayWithObjects: [NSArray arrayWithObjects: [self d], [self generateMySecretObject],nil], [NSArray arrayWithObjects: [self generateMySecretObject], [self generateMySecretObject],nil],nil]; for (int k=0; k<[self.myArray count]; k++) { for(int s = 0; s<[[self.myArray objectAtIndex:k] count]; s++){ [[[self.myArray objectAtIndex:k] objectAtIndex:s] setAttribute:[self generateSecertAttribute]]; } } As you can see this is a simple 2*2 array, but it takes me lots of code to assign the NSArray in very first place, because I found that the NSArray can't assign the size at very beginning. Also, I want to set attribute one by one. I can't think of if my array change to 10*10. How long it could be. So, I hope you guys can give me some suggestions on shorten the code, and more readable. thz

    Read the article

  • cocos2d MFMailComposeViewController

    - by MRaguse
    hi, i tried to insert a mail tool in my app.... my app is based on the cocos2d engine the Toolbar (at the top -cancel,send...) is visible but i can't see the other parts of the mfMailComposerViewController view :-( code: -(void)displayComposerSheet { MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init]; picker.mailComposeDelegate = self; [picker setSubject:@"my message"]; // Set up recipients NSArray *toRecipients = [NSArray arrayWithObject:@"[email protected]"]; NSArray *ccRecipients = [NSArray arrayWithObjects:@"[email protected]", @"[email protected]", nil]; NSArray *bccRecipients = [NSArray arrayWithObject:@"[email protected]"]; [picker setToRecipients:toRecipients]; [picker setCcRecipients:ccRecipients]; [picker setBccRecipients:bccRecipients]; // Attach an image to the email UIImage *screenshot = [[Director sharedDirector] screenShotUIImage]; NSData *myData = UIImagePNGRepresentation(screenshot); [picker addAttachmentData:myData mimeType:@"image/png" fileName:@"AdMotiv"]; // Fill out the email body text NSString *emailBody = @"test"; [picker setMessageBody:emailBody isHTML:NO]; [[picker view] setFrame:CGRectMake(0.0f,0.0f,320.0f, 480.0f)]; [[picker view] setTransform:CGAffineTransformIdentity]; [[picker view] setBounds:CGRectMake(0.0f,0.0f,320.0f, 480.0f)]; //[[[VariableStore sharedInstance] parentView] setTransform: CGAffineTransformIdentity]; //[[[VariableStore sharedInstance] parentView] setBounds : CGRectMake(0.0f, 0.0f, 480.0f, 320.0f)]; UITextField *textfeld = [[UITextField alloc] initWithFrame:CGRectMake(50.0f, 50.0f, 100.0f, 100.0f)]; [[picker view] addSubview:textfeld]; [[[VariableStore sharedInstance] window]addSubview:picker.view]; [[[VariableStore sharedInstance] window] makeKeyAndVisible]; [picker release]; }

    Read the article

  • iphone - why is this flip animation using layers not working?

    - by Digital Robot
    I would like to make an animation that goes like this: imagine a picture sitting on a shelve. It drops from the shelve and as it falls it rotates along the horizontal axis and translates along the vertical axis. I would like to do this with perspective and the back side should be the image reversed, like the picture is a kind of slide. I have done this: CALayer* layer = myImageView.layer; layer.doubleSided = YES; CAKeyframeAnimation* animationTransform = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; CATransform3D startTransform = CATransform3DIdentity; CATransform3D endTransform = CATransform3DTranslate (layer.transform, 0.0f, 200.0f, 0.0f); endTransform = CATransform3DRotate (endTransform, degreesToRadian(350.0f), 1.0f, 0.0f, 0.0f); endTransform.m34 = 1.0 / -500; NSArray *values = [NSArray arrayWithObjects: [NSValue valueWithCATransform3D:startTransform], [NSValue valueWithCATransform3D:endTransform], nil]; [animationTransform setValues:values]; NSArray *tempos = [NSArray arrayWithObjects: [NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:0.7f], nil]; [animationTransform setKeyTimes:tempos]; NSArray *timing = [NSArray arrayWithObjects: [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut], nil]; [animationTransform setTimingFunctions:timing]; animationTransform.fillMode = kCAFillModeRemoved; animationTransform.removedOnCompletion = YES; animationTransform.repeatCount = 1; animationTransform.duration = 3.7f; animationTransform.cumulative = YES; the result of this has nothing to do with anything. The result is: the image translates down an inch on the screen and then up half inch. Then it disappears and appears at its starting position again. What am I missing? thanks

    Read the article

  • How do i rotate a CALayer around a diagonal line?

    - by Mattias Wadman
    Hi. I'm trying to implement a flip animation to be used in board game like iPhone-application. The animation is supposed to look like a game piece that rotates and changes to the color of its back (kind of like an Reversi piece). I've managed to create an animation that flips the piece around its orthogonal axis, but when I try to flip it around a diagonal axis by changing the rotation around the z-axis the actual image also gets rotated (not surprisingly). Instead I would like to rotate the image "as is" around a diagonal axis. I have tried to change layer.sublayerTransform but with no success. Here is my current implementation. It works by doing a trick to resolve the issue of getting a mirrored image at the end of the animation. The solution is to not actually rotate the layer 180 degrees, instead it rotates it 90 degrees, changes image and then rotates it back. + (void)flipLayer:(CALayer *)layer toImage:(CGImageRef)image withAngle:(double)angle { const float duration = 0.5f; CAKeyframeAnimation *diag = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"]; diag.duration = duration; diag.values = [NSArray arrayWithObjects: [NSNumber numberWithDouble:angle], [NSNumber numberWithDouble:0.0f], nil]; diag.keyTimes = [NSArray arrayWithObjects: [NSNumber numberWithDouble:0.0f], [NSNumber numberWithDouble:1.0f], nil]; diag.calculationMode = kCAAnimationDiscrete; CAKeyframeAnimation *flip = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.y"]; flip.duration = duration; flip.values = [NSArray arrayWithObjects: [NSNumber numberWithDouble:0.0f], [NSNumber numberWithDouble:M_PI / 2], [NSNumber numberWithDouble:0.0f], nil]; flip.keyTimes = [NSArray arrayWithObjects: [NSNumber numberWithDouble:0.0f], [NSNumber numberWithDouble:0.5f], [NSNumber numberWithDouble:1.0f], nil]; flip.calculationMode = kCAAnimationLinear; CAKeyframeAnimation *replace = [CAKeyframeAnimation animationWithKeyPath:@"contents"]; replace.duration = duration / 2; replace.beginTime = duration / 2; replace.values = [NSArray arrayWithObjects:(id)image, nil]; replace.keyTimes = [NSArray arrayWithObjects: [NSNumber numberWithDouble:0.0f], nil]; replace.calculationMode = kCAAnimationDiscrete; CAAnimationGroup *group = [CAAnimationGroup animation]; group.removedOnCompletion = NO; group.duration = duration; group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; group.animations = [NSArray arrayWithObjects:diag, flip, replace, nil]; group.fillMode = kCAFillModeForwards; [layer addAnimation:group forKey:nil]; }

    Read the article

  • How do i rotate a CALayer around a diagonal axis?

    - by Mattias Wadman
    Hi, im trying to implement a flip animation to be used in board game like application. The animation is suppose to look like a game piece that rotate and change to the color of its back. I have managed to get a animation that flips around orthogonal axis, but when i try to flip around a diagonal axis by changing the rotation around the z-axis not surprisingly the actual image also gets rotated. Instead i would like to rotate the image as it is around a diagonal axis. I have tried to change layer.sublayerTransform but with no success. Here is the current implementation. It works by doing a trick to resolve the issue of getting a mirrored image at the end of the animation. The solution is to not actually rotate the layer 180 degrees, instead it rotates it 90 degrees, changes image and then rotates it back. + (void)flipLayer:(CALayer *)layer toImage:(CGImageRef)image withAngle:(double)angle { const float duration = 0.5f; CAKeyframeAnimation *diag = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"]; diag.duration = duration; diag.values = [NSArray arrayWithObjects: [NSNumber numberWithDouble:angle], [NSNumber numberWithDouble:0.0f], nil]; diag.keyTimes = [NSArray arrayWithObjects: [NSNumber numberWithDouble:0.0f], [NSNumber numberWithDouble:1.0f], nil]; diag.calculationMode = kCAAnimationDiscrete; CAKeyframeAnimation *flip = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.y"]; flip.duration = duration; flip.values = [NSArray arrayWithObjects: [NSNumber numberWithDouble:0.0f], [NSNumber numberWithDouble:M_PI / 2], [NSNumber numberWithDouble:0.0f], nil]; flip.keyTimes = [NSArray arrayWithObjects: [NSNumber numberWithDouble:0.0f], [NSNumber numberWithDouble:0.5f], [NSNumber numberWithDouble:1.0f], nil]; flip.calculationMode = kCAAnimationLinear; CAKeyframeAnimation *replace = [CAKeyframeAnimation animationWithKeyPath:@"contents"]; replace.duration = duration / 2; replace.beginTime = duration / 2; replace.values = [NSArray arrayWithObjects:(id)image, nil]; replace.keyTimes = [NSArray arrayWithObjects: [NSNumber numberWithDouble:0.0f], nil]; replace.calculationMode = kCAAnimationDiscrete; CAAnimationGroup *group = [CAAnimationGroup animation]; group.removedOnCompletion = NO; group.duration = duration; group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; group.animations = [NSArray arrayWithObjects:diag, flip, replace, nil]; group.fillMode = kCAFillModeForwards; [layer addAnimation:group forKey:nil]; }

    Read the article

  • Updating UISearchDisplayController with Core Data results using GCD

    - by Brian Halpin
    I'm having trouble displaying the results from Core Data in my UISearchDisplayController when I implement GCD. Without it, it works, but obviously blocks the UI. In my SearchTableViewController I have the following two methods: - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { // Tell the table data source to reload when text changes [self filterContentForSearchText:searchString]; // Return YES to cause the search result table view to be reloaded. return YES; } // Update the filtered array based on the search text -(void)filterContentForSearchText:(NSString*)searchText { // Remove all objects from the filtered search array [self.filteredLocationsArray removeAllObjects]; NSPredicate *predicate = [CoreDataMaster predicateForLocationUsingSearchText:@"Limerick"]; CoreDataMaster *coreDataMaster = [[CoreDataMaster alloc] init]; // Filter the array using NSPredicate self.filteredLocationsArray = [NSMutableArray arrayWithArray: [coreDataMaster fetchResultsFromCoreDataEntity:@"City" UsingPredicate:predicate]]; } You can probably guess that my problem is with returning the array from [coreDataMaster fetchResultsFromCoreDataEntity]. Below is the method: - (NSArray *)fetchResultsFromCoreDataEntity:(NSString *)entity UsingPredicate:(NSPredicate *)predicate { NSMutableArray *fetchedResults = [[NSMutableArray alloc] init]; dispatch_queue_t coreDataQueue = dispatch_queue_create("com.coredata.queue", DISPATCH_QUEUE_SERIAL); dispatch_async(coreDataQueue, ^{ NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entity inManagedObjectContext:self.managedObjectContext]; NSSortDescriptor *nameSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObjects:nameSort, nil]; [fetchRequest setEntity:entityDescription]; [fetchRequest setSortDescriptors:sortDescriptors]; // Check if predicate is set if (predicate) { [fetchRequest setPredicate:predicate]; } NSError *error = nil; NSArray *fetchedManagedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; for (City *city in fetchedManagedObjects) { [fetchedResults addObject:city]; } NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSArray arrayWithArray:fetchedResults] forKey:@"results"]; [[NSNotificationCenter defaultCenter] postNotificationName:@"fetchResultsComplete" object:nil userInfo:userInfo]; }); return [NSArray arrayWithArray:fetchedResults]; } So the thread hasn't finished executing by the time it returns the results to self.filteredLocationsArray. I've tried added a NSNotification which passes the NSDictionary to this method: - (void)updateSearchResults:(NSNotification *)notification { NSDictionary *userInfo = notification.userInfo; NSArray *array = [userInfo objectForKey:@"results"]; self.filteredLocationsArray = [NSMutableArray arrayWithArray:array]; [self.tableView reloadData]; } I've also tried refreshing the searchViewController like [self.searchDisplayController.searchResultsTableView reloadData]; but to no avail. I'd really appreciate it if someone could point me in the right direction and show me where I might be going wrong. Thanks

    Read the article

  • Core Data - JSON (TouchJSON) on iPhone

    - by Urizen
    I have the following code which seems to go on indefinitely until the app crashes. It seems to happen with the recursion in the datastructureFromManagedObject method. I suspect that this method: 1) looks at the first managed object and follows any relationship property recursively. 2) examines the object at the other end of the relationship found at point 1 and repeats the process. Is it possible that if managed object A has a to-many relationship with object B and that relationship is two-way (i.e an inverse to-one relationship to A from B - e.g. one department has many employees but each employee has only one department) that the following code gets stuck in infinite recursion as it follows the to-one relationship from object B back to object A and so on. If so, can anyone provide a fix for this so that I can get my whole object graph of managed objects converted to JSON. #import "JSONUtils.h" @implementation JSONUtils - (NSDictionary*)dataStructureFromManagedObject:(NSManagedObject *)managedObject { NSDictionary *attributesByName = [[managedObject entity] attributesByName]; NSDictionary *relationshipsByName = [[managedObject entity] relationshipsByName]; //getting the values correspoinding to the attributes collected in attributesByName NSMutableDictionary *valuesDictionary = [[managedObject dictionaryWithValuesForKeys:[attributesByName allKeys]] mutableCopy]; //sets the name for the entity being encoded to JSON [valuesDictionary setObject:[[managedObject entity] name] forKey:@"ManagedObjectName"]; NSLog(@"+++++++++++++++++> before the for loop"); //looks at each relationship for the given managed object for (NSString *relationshipName in [relationshipsByName allKeys]) { NSLog(@"The relationship name = %@",relationshipName); NSRelationshipDescription *description = [relationshipsByName objectForKey:relationshipName]; if (![description isToMany]) { NSLog(@"The relationship is NOT TO MANY!"); [valuesDictionary setObject:[self dataStructureFromManagedObject:[managedObject valueForKey:relationshipName]] forKey:relationshipName]; continue; } NSSet *relationshipObjects = [managedObject valueForKey:relationshipName]; NSMutableArray *relationshipArray = [[NSMutableArray alloc] init]; for (NSManagedObject *relationshipObject in relationshipObjects) { [relationshipArray addObject:[self dataStructureFromManagedObject:relationshipObject]]; } [valuesDictionary setObject:relationshipArray forKey:relationshipName]; } return [valuesDictionary autorelease]; } - (NSArray*)dataStructuresFromManagedObjects:(NSArray*)managedObjects { NSMutableArray *dataArray = [[NSArray alloc] init]; for (NSManagedObject *managedObject in managedObjects) { [dataArray addObject:[self dataStructureFromManagedObject:managedObject]]; } return [dataArray autorelease]; } //method to call for obtaining JSON structure - i.e. public interface to this class - (NSString*)jsonStructureFromManagedObjects:(NSArray*)managedObjects { NSLog(@"-------------> just before running the recursive method"); NSArray *objectsArray = [self dataStructuresFromManagedObjects:managedObjects]; NSLog(@"-------------> just before running the serialiser"); NSString *jsonString = [[CJSONSerializer serializer] serializeArray:objectsArray]; return jsonString; } - (NSManagedObject*)managedObjectFromStructure:(NSDictionary*)structureDictionary withManagedObjectContext:(NSManagedObjectContext*)moc { NSString *objectName = [structureDictionary objectForKey:@"ManagedObjectName"]; NSManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:objectName inManagedObjectContext:moc]; [managedObject setValuesForKeysWithDictionary:structureDictionary]; for (NSString *relationshipName in [[[managedObject entity] relationshipsByName] allKeys]) { NSRelationshipDescription *description = [[[managedObject entity]relationshipsByName] objectForKey:relationshipName]; if (![description isToMany]) { NSDictionary *childStructureDictionary = [structureDictionary objectForKey:relationshipName]; NSManagedObject *childObject = [self managedObjectFromStructure:childStructureDictionary withManagedObjectContext:moc]; [managedObject setValue:childObject forKey:relationshipName]; continue; } NSMutableSet *relationshipSet = [managedObject mutableSetValueForKey:relationshipName]; NSArray *relationshipArray = [structureDictionary objectForKey:relationshipName]; for (NSDictionary *childStructureDictionary in relationshipArray) { NSManagedObject *childObject = [self managedObjectFromStructure:childStructureDictionary withManagedObjectContext:moc]; [relationshipSet addObject:childObject]; } } return managedObject; } //method to call for obtaining managed objects from JSON structure - i.e. public interface to this class - (NSArray*)managedObjectsFromJSONStructure:(NSString *)json withManagedObjectContext:(NSManagedObjectContext*)moc { NSError *error = nil; NSArray *structureArray = [[CJSONDeserializer deserializer] deserializeAsArray:[json dataUsingEncoding:NSUTF32BigEndianStringEncoding] error:&error]; NSAssert2(error == nil, @"Failed to deserialize\n%@\n%@", [error localizedDescription], json); NSMutableArray *objectArray = [[NSMutableArray alloc] init]; for (NSDictionary *structureDictionary in structureArray) { [objectArray addObject:[self managedObjectFromStructure:structureDictionary withManagedObjectContext:moc]]; } return [objectArray autorelease]; } @end

    Read the article

  • Accessing multiple view controllers in page controller

    - by Apple Delegates
    I am showing view in ipad like a book, single view shows two view. I want to add more views so that when view flipped third and fourth view appears and further. I am using the code below to do so. I am adding ViewControllers to array it got kill at orientation method at this line " ContentViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];". - (void)viewDidLoad { [super viewDidLoad]; //Instantiate the model array self.modelArray = [[NSMutableArray alloc] init]; for (int index = 1; index <= 12 ; index++) { [self.modelArray addObject:[NSString stringWithFormat:@"Page %d",index]]; } //Step 1 //Instantiate the UIPageViewController. self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil]; //Step 2: //Assign the delegate and datasource as self. self.pageViewController.delegate = self; self.pageViewController.dataSource = self; //Step 3: //Set the initial view controllers. ViewOne *one = [[ViewOne alloc]initWithNibName:@"ViewOne" bundle:nil]; viewTwo *two = [[viewTwo alloc]initWithNibName:@"ViewTwo" bundle:nil]; ContentViewController *contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentViewController" bundle:nil]; contentViewController.labelContents = [self.modelArray objectAtIndex:0]; // NSArray *viewControllers = [NSArray arrayWithObject:contentViewController]; viewControllers = [NSArray arrayWithObjects:contentViewController,one,two,nil]; [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil]; //Step 4: //ViewController containment steps //Add the pageViewController as the childViewController [self addChildViewController:self.pageViewController]; //Add the view of the pageViewController to the current view [self.view addSubview:self.pageViewController.view]; //Call didMoveToParentViewController: of the childViewController, the UIPageViewController instance in our case. [self.pageViewController didMoveToParentViewController:self]; //Step 5: // set the pageViewController's frame as an inset rect. CGRect pageViewRect = self.view.bounds; pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0); self.pageViewController.view.frame = pageViewRect; //Step 6: //Assign the gestureRecognizers property of our pageViewController to our view's gestureRecognizers property. self.view.gestureRecognizers = self.pageViewController.gestureRecognizers; } - (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation { if(UIInterfaceOrientationIsPortrait(orientation)) { //Set the array with only 1 view controller UIViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0]; NSArray *viewControllers = [NSArray arrayWithObject:currentViewController]; [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL]; //Important- Set the doubleSided property to NO. self.pageViewController.doubleSided = NO; //Return the spine location return UIPageViewControllerSpineLocationMin; } else { // NSArray *viewControllers = nil; ContentViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0]; NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)currentViewController labelContents]]; if(currentIndex == 0 || currentIndex %2 == 0) { UIViewController *nextViewController = [self pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController]; viewControllers = [NSArray arrayWithObjects:currentViewController, nextViewController, nil]; } else { UIViewController *previousViewController = [self pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController]; viewControllers = [NSArray arrayWithObjects:previousViewController, currentViewController, nil]; } //Now, set the viewControllers property of UIPageViewController [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL]; return UIPageViewControllerSpineLocationMid; } }

    Read the article

  • iOS TableView crash loading different data

    - by jollyr0ger
    Hi to all! I'm developing a simple iOS app where there is a table view with some categories (CategoryViewController). When clicking one of this category the view will be passed to a RecipesListController with another table view with recipes. This recipes are loaded from different plist based on the category clicked. The first time I click on a category, the recipes list is loaded and shown correctely. If i back to the category list and click any of the category (also the same again) the app crash. And I don't know how. The viewWillAppear is ececuted correctely but after crash. Can you help me? If you need the entire project I can zip it for you. Ok? Here is the code of the CategoryViewController.h #import <Foundation/Foundation.h> #import "RecipeRowViewController.h" @class RecipesListController; @interface CategoryViewController : UITableViewController { NSArray *recipeCategories; RecipesListController *childController; } @property (nonatomic, retain) NSArray *recipeCategories; @end The CategoryViewControoler.m #import "CategoryViewCotroller.h" #import "NavAppDelegate.h" #import "RecipesListController.h" @implementation CategoryViewController @synthesize recipeCategories; - (void)viewDidLoad { // Create the categories NSArray *array = [[NSArray alloc] initWithObjects:@"Antipasti", @"Focacce", @"Primi", @"Secondi", @"Contorni", @"Dolci", nil]; self.recipeCategories = array; [array release]; // Set background image UIImageView *bgImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sfondo_app.png"]]; [self.tableView setBackgroundView:bgImg]; [bgImg release]; [self.tableView reloadData]; [super viewDidLoad]; } - (void)viewDidUnload { self.recipeCategories = nil; // [childController release]; [super viewDidUnload]; } - (void)dealloc { [recipeCategories release]; // [childController release]; [super dealloc]; } #pragma mark - #pragma mark Table data source methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [recipeCategories count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellId = @"RecipesCategoriesCellId"; // Try to reuse a cell or create a new one UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId] autorelease]; } // Get the right value and assign to the cell NSUInteger row = [indexPath row]; NSString *rowString = [recipeCategories objectAtIndex:row]; cell.textLabel.text = rowString; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; [rowString release]; return cell; } #pragma mark - #pragma mark Table view delegate methods - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (childController == nil) { childController = [[RecipesListController alloc] initWithStyle:UITableViewStyleGrouped]; } childController.title = @"Ricette"; childController.category = [indexPath row]; [self.navigationController pushViewController:childController animated:YES]; } @end The RecipesListController.h #import <Foundation/Foundation.h> #import "RecipeRowViewController.h" #define kRecipeArrayLink 0 #define kRecipeArrayDifficulty 1 #define kRecipeArrayFoodType 2 #define kRecipeAntipasti 0 #define kRecipeFocacce 1 #define kRecipePrimi 2 #define kRecipeSecondi 3 #define kRecipeContorni 4 #define kRecipeDolci 5 @class DisclosureDetailController; @interface RecipesListController : UITableViewController { NSInteger category; NSDictionary *recipesArray; NSArray *recipesNames; NSArray *recipesLinks; DisclosureDetailController *childController; } @property (nonatomic) NSInteger category; @property (nonatomic, retain) NSDictionary *recipesArray; @property (nonatomic, retain) NSArray *recipesNames; @property (nonatomic, retain) NSArray *recipesLinks; @end The RecipesListcontroller.m #import "RecipesListController.h" #import "NavAppDelegate.h" #import "DisclosureDetailController.h" @implementation RecipesListController @synthesize category, recipesArray, recipesNames, recipesLinks; - (void)viewDidLoad { // Set background image UIImageView *bgImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sfondo_app.png"]]; [self.tableView setBackgroundView:bgImg]; [bgImg release]; [self.tableView reloadData]; [super viewDidLoad]; } - (void)viewWillAppear:(BOOL)animated { if (self.recipesArray != nil) { // Release the arrays [self.recipesArray release]; [self.recipesNames release]; } // Load the dictionary NSString *path = nil; // Load a different dictionary, based on the category if (self.category == kRecipeAntipasti) { path = [[NSBundle mainBundle] pathForResource:@"recipes_antipasti" ofType:@"plist"]; } else if (self.category == kRecipeFocacce) { path = [[NSBundle mainBundle] pathForResource:@"recipes_focacce" ofType:@"plist"]; } else if (self.category == kRecipePrimi) { path = [[NSBundle mainBundle] pathForResource:@"recipes_primi" ofType:@"plist"]; } else if (self.category == kRecipeSecondi) { path = [[NSBundle mainBundle] pathForResource:@"recipes_secondi" ofType:@"plist"]; } else if (self.category == kRecipeContorni) { path = [[NSBundle mainBundle] pathForResource:@"recipes_contorni" ofType:@"plist"]; } else if (self.category == kRecipeDolci) { path = [[NSBundle mainBundle] pathForResource:@"recipes_dolci" ofType:@"plist"]; } NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path]; self.recipesArray = dict; [dict release]; // Save recipes names NSArray *array = [[recipesArray allKeys] sortedArrayUsingSelector: @selector(compare:)]; self.recipesNames = array; [self.tableView reloadData]; [super viewWillAppear:animated]; } - (void)viewDidUnload { self.recipesArray = nil; self.recipesNames = nil; self.recipesLinks = nil; // [childController release]; [super viewDidUnload]; } - (void)dealloc { [recipesArray release]; [recipesNames release]; [recipesLinks release]; // [childController release]; [super dealloc]; } #pragma mark - #pragma mark Table data source methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [recipesNames count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *RecipesListCellId = @"RecipesListCellId"; // Try to reuse a cell or create a new one UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RecipesListCellId]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RecipesListCellId] autorelease]; } // Get the right value and assign to the cell NSUInteger row = [indexPath row]; NSString *rowString = [recipesNames objectAtIndex:row]; cell.textLabel.text = rowString; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; [rowString release]; return cell; } #pragma mark - #pragma mark Table view delegate methods - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (childController == nil) { childController = [[DisclosureDetailController alloc] initWithNibName:@"DisclosureDetail" bundle:nil]; } childController.title = @"Dettagli"; NSUInteger row = [indexPath row]; childController.recipeName = [recipesNames objectAtIndex:row]; NSArray *recipeRawArray = [recipesArray objectForKey:childController.recipeName]; childController.recipeLink = [recipeRawArray objectAtIndex:kRecipeArrayLink]; childController.recipeDifficulty = [recipeRawArray objectAtIndex:kRecipeArrayDifficulty]; [self.navigationController pushViewController:childController animated:YES]; } @end This is the crash log Program received signal: “EXC_BAD_ACCESS”. (gdb) bt #0 0x00f0da63 in objc_msgSend () #1 0x04b27ca0 in ?? () #2 0x00002665 in -[RecipesListController viewWillAppear:] (self=0x4b38a00, _cmd=0x6d81a2, animated=1 '\001') at /Users/claudiocanino/Documents/iOS/CottoMangiato/Classes/RecipesListController.m:67 #3 0x00370c9a in -[UINavigationController _startTransition:fromViewController:toViewController:] () #4 0x0036b606 in -[UINavigationController _startDeferredTransitionIfNeeded] () #5 0x0037283e in -[UINavigationController pushViewController:transition:forceImmediate:] () #6 0x04f49549 in -[UINavigationControllerAccessibility(SafeCategory) pushViewController:transition:forceImmediate:] () #7 0x0036b4a0 in -[UINavigationController pushViewController:animated:] () #8 0x00003919 in -[CategoryViewController tableView:didSelectRowAtIndexPath:] (self=0x4b27ca0, _cmd=0x6d19e3, tableView=0x500c200, indexPath=0x4b2d650) at /Users/claudiocanino/Documents/iOS/CottoMangiato/Classes/CategoryViewCotroller.m:104 #9 0x0032a794 in -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] () #10 0x00320d50 in -[UITableView _userSelectRowAtPendingSelectionIndexPath:] () #11 0x000337f6 in __NSFireDelayedPerform () #12 0x00d8cfe3 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ () #13 0x00d8e594 in __CFRunLoopDoTimer () #14 0x00ceacc9 in __CFRunLoopRun () #15 0x00cea240 in CFRunLoopRunSpecific () #16 0x00cea161 in CFRunLoopRunInMode () #17 0x016e0268 in GSEventRunModal () #18 0x016e032d in GSEventRun () #19 0x002c342e in UIApplicationMain () #20 0x00001c08 in main (argc=1, argv=0xbfffef58) at /Users/claudiocanino/Documents/iOS/CottoMangiato/main.m:15 Another bt log: (gdb) bt #0 0x00cd76a1 in __CFBasicHashDeallocate () #1 0x00cc2bcb in _CFRelease () #2 0x00002dd6 in -[RecipesListController setRecipesArray:] (self=0x6834d50, _cmd=0x4293, _value=0x4e3bc70) at /Users/claudiocanino/Documents/iOS/CottoMangiato/Classes/RecipesListController.m:16 #3 0x00002665 in -[RecipesListController viewWillAppear:] (self=0x6834d50, _cmd=0x6d81a2, animated=1 '\001') at /Users/claudiocanino/Documents/iOS/CottoMangiato/Classes/RecipesListController.m:67 #4 0x00370c9a in -[UINavigationController _startTransition:fromViewController:toViewController:] () #5 0x0036b606 in -[UINavigationController _startDeferredTransitionIfNeeded] () #6 0x0037283e in -[UINavigationController pushViewController:transition:forceImmediate:] () #7 0x091ac549 in -[UINavigationControllerAccessibility(SafeCategory) pushViewController:transition:forceImmediate:] () #8 0x0036b4a0 in -[UINavigationController pushViewController:animated:] () #9 0x00003919 in -[CategoryViewController tableView:didSelectRowAtIndexPath:] (self=0x4b12970, _cmd=0x6d19e3, tableView=0x5014400, indexPath=0x4b2bd00) at /Users/claudiocanino/Documents/iOS/CottoMangiato/Classes/CategoryViewCotroller.m:104 #10 0x0032a794 in -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] () #11 0x00320d50 in -[UITableView _userSelectRowAtPendingSelectionIndexPath:] () #12 0x000337f6 in __NSFireDelayedPerform () #13 0x00d8cfe3 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ () #14 0x00d8e594 in __CFRunLoopDoTimer () #15 0x00ceacc9 in __CFRunLoopRun () #16 0x00cea240 in CFRunLoopRunSpecific () #17 0x00cea161 in CFRunLoopRunInMode () #18 0x016e0268 in GSEventRunModal () #19 0x016e032d in GSEventRun () #20 0x002c342e in UIApplicationMain () #21 0x00001c08 in main (argc=1, argv=0xbfffef58) at /Users/claudiocanino/Documents/iOS/CottoMangiato/main.m:15 Thanks

    Read the article

  • UITableView insertRowsAtIndexPaths out of order

    - by bschlenk
    I currently have a UISegmentedControl set to add/remove table view cells when its value changes. Removing cells works perfectly, however when I insert cells they're in reverse order every other time. NSArray *addindexes = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:2 inSection:0], [NSIndexPath indexPathForRow:3 inSection:0], [NSIndexPath indexPathForRow:4 inSection:0], nil]; NSArray *removeindexes = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:2 inSection:0], [NSIndexPath indexPathForRow:3 inSection:0], [NSIndexPath indexPathForRow:4 inSection:0], nil]; [self.tableView beginUpdates]; switch (switchType.selectedSegmentIndex) { case 0: [self.tableView insertRowsAtIndexPaths:addindexes withRowAnimation:UITableViewRowAnimationTop]; break; case 1: [self.tableView deleteRowsAtIndexPaths:removeindexes withRowAnimation:UITableViewRowAnimationTop]; break; default: break; } [self.tableView endUpdates];} For example, every other time I add/remove cells they're in reverse order. (4, 3, 2 instead of 2, 3, 4) 1) Remove cells- add cells- correct order 2) Remove cells- add cells- incorrect order 3) Remove cells- add cells- correct order

    Read the article

  • writing NSDictionary to plist

    - by ADude
    Hi I'm trying to write an NSDictionary to a plist but when I open the plist no data has been written to it. From the log my path looks correct and my code is pretty standard. Any ideas? NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil]; NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", @"value3", nil]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; for (id key in dictionary) { NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]); } NSString *path = [[NSBundle mainBundle] pathForResource:@"FormData" ofType:@"plist"]; NSLog(@"path:%@", path); [dictionary writeToFile:path atomically:YES];

    Read the article

  • Objective-C : Sorting NSMutableArray containing NSMutableArrays

    - by Dough
    Hi ! I'm currently using NSMutableArrays in my developments to store some data taken from an HTTP Servlet. Everything is fine since now I have to sort what is in my array. This is what I do : NSMutableArray *array = [[NSMutableArray arrayWithObjects:nil] retain]; [array addObject:[NSArray arrayWithObjects: "Label 1", 1, nil]]; [array addObject:[NSArray arrayWithObjects: "Label 2", 4, nil]]; [array addObject:[NSArray arrayWithObjects: "Label 3", 2, nil]]; [array addObject:[NSArray arrayWithObjects: "Label 4", 6, nil]]; [array addObject:[NSArray arrayWithObjects: "Label 5", 0, nil]]; First column contain a Label and 2nd one is a score I want the array to be sorted descending. Is the way I am storing my data a good one ? Is there a better way to do this than using NSMutableArrays in NSMutableArray ? I'm new to iPhone dev, I've seen some code about sorting but didn't feel good with that. Thanks in advance for your answers !

    Read the article

  • Using Objective-C Blocks

    - by Sean
    Today I was experimenting with Objective-C's blocks so I thought I'd be clever and add to NSArray a few functional-style collection methods that I've seen in other languages: @interface NSArray (FunWithBlocks) - (NSArray *)collect:(id (^)(id obj))block; - (NSArray *)select:(BOOL (^)(id obj))block; - (NSArray *)flattenedArray; @end The collect: method takes a block which is called for each item in the array and expected to return the results of some operation using that item. The result is the collection of all of those results. (If the block returns nil, nothing is added to the result set.) The select: method will return a new array with only the items from the original that, when passed as an argument to the block, the block returned YES. And finally, the flattenedArray method iterates over the array's items. If an item is an array, it recursively calls flattenedArray on it and adds the results to the result set. If the item isn't an array, it adds the item to the result set. The result set is returned when everything is finished. So now that I had some infrastructure, I needed a test case. I decided to find all package files in the system's application directories. This is what I came up with: NSArray *packagePaths = [[[NSSearchPathForDirectoriesInDomains(NSAllApplicationsDirectory, NSAllDomainsMask, YES) collect:^(id path) { return (id)[[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil] collect:^(id file) { return (id)[path stringByAppendingPathComponent:file]; }]; }] flattenedArray] select:^(id fullPath) { return [[NSWorkspace sharedWorkspace] isFilePackageAtPath:fullPath]; }]; Yep - that's all one line and it's horrid. I tried a few approaches at adding newlines and indentation to try to clean it up, but it still feels like the actual algorithm is lost in all the noise. I don't know if it's just a syntax thing or my relative in-experience with using a functional style that's the problem, though. For comparison, I decided to do it "the old fashioned way" and just use loops: NSMutableArray *packagePaths = [NSMutableArray new]; for (NSString *searchPath in NSSearchPathForDirectoriesInDomains(NSAllApplicationsDirectory, NSAllDomainsMask, YES)) { for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:searchPath error:nil]) { NSString *packagePath = [searchPath stringByAppendingPathComponent:file]; if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:packagePath]) { [packagePaths addObject:packagePath]; } } } IMO this version was easier to write and is more readable to boot. I suppose it's possible this was somehow a bad example, but it seems like a legitimate way to use blocks to me. (Am I wrong?) Am I missing something about how to write or structure Objective-C code with blocks that would clean this up and make it clearer than (or even just as clear as) the looped version?

    Read the article

  • iPhone OSStatus -25308 or errSecInteractionNotAllowed SFHFKeychainUtils

    - by George Octavio
    Hi again guys. I'm trying to access my iPhone's device keychain. I want to access in order to create a simple user-password value intended for a log in function. This is the code I'm using from SFHFKeychainUtils NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrService, kSecAttrLabel, kSecAttrAccount, kSecValueData, nil] autorelease]; NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, serviceName, serviceName, @"TestUser", @"TestPass", nil] autorelease]; NSDictionary *query = [[[NSDictionary alloc] initWithObjects: objects forKeys: keys] autorelease]; OSStatus status = SecItemAdd((CFDictionaryRef) query, NULL); } else if (status != noErr) { //Output to screen with error code goes here return NO; } return YES; } The error code I'm getting is OSStatus-25308 or errSecInteractionNotAllowed. I'm guessing this means I don't actually have access to my iPhone's keychain? Is there a way to allow access? Thanks for your time.

    Read the article

  • EXC_BAD_ACCESS on startAsynchronous request using ASIFormDataRequest

    - by user280556
    I am getting EXC_BAD_ACCESS on the Line: [asiUsernameRequest startAsynchronous]; in this code. Spent hours trying to figure it out, but no solution. Any idea? NSString *usernameValue = (NSString*)usernameField.text; NSLog(@"username selected: %@", usernameValue); NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com/api/usernameCheck"]; //ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; asiUsernameRequest = [[[ASIFormDataRequest alloc] initWithURL:url] retain]; [asiUsernameRequest setPostValue:usernameValue forKey:@"username"]; NSArray *objects = [NSArray arrayWithObjects:@"usernameCheck", nil]; NSArray *keys = [NSArray arrayWithObjects:@"action", nil]; asiUsernameRequest.userInfo = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; [asiUsernameRequest setDelegate:self]; [asiUsernameRequest startAsynchronous];

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >