Search Results

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

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

  • Objective-C Getter Memory Management

    - by Marian André
    I'm fairly new to Objective-C and am not sure how to correctly deal with memory management in the following scenario: I have a Core Data Entity with a to-many relationship for the key "children". In order to access the children as an array, sorted by the column "position", I wrote the model class this way: @interface AbstractItem : NSManagedObject { NSArray * arrangedChildren; } @property (nonatomic, retain) NSSet * children; @property (nonatomic, retain) NSNumber * position; @property (nonatomic, retain) NSArray * arrangedChildren; @end @implementation AbstractItem @dynamic children; @dynamic position; @synthesize arrangedChildren; - (NSArray*)arrangedChildren { NSArray* unarrangedChildren = [[self.children allObjects] retain]; NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"position" ascending:YES]; [arrangedChildren release]; arrangedChildren = [unarrangedChildren sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; [sortDescriptor release]; [unarrangedChildren release]; return [arrangedChildren retain]; } @end I'm not sure whether or not to retain unarrangedChildren and the returned arrangedChildren (first and last line of the arrangedChildren getter). Does the NSSet allObjects method already return a retained array? It's probably too late and I have a coffee overdose. I'd be really thankful if someone could point me in the right direction. I guess I'm missing vital parts of memory management knowledge and I will definitely look into it thoroughly.

    Read the article

  • initializer not constant?

    - by fuzzygoat
    Quick question if I may: I am just curious about the following (see below) Xcode says "initializer element is not constant" why this does not work, I guess its the NSArray ... static NSArray *stuffyNames = [NSArray arrayWithObjects:@"Ted",@"Dog",@"Snosa",nil]; and this does ... static NSString *stuffyNames[3] = {@"Ted",@"Dog",@"Snosa"}; gary

    Read the article

  • Several Objective-C objects become Invalid for no reason, sometimes.

    - by farnsworth
    - (void)loadLocations { NSString *url = @"<URL to a text file>"; NSStringEncoding enc = NSUTF8StringEncoding; NSString *locationString = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:url] usedEncoding:&enc error:nil]; NSArray *lines = [locationString componentsSeparatedByString:@"\n"]; for (int i=0; i<[lines count]; i++) { NSString *line = [lines objectAtIndex:i]; NSArray *components = [line componentsSeparatedByString:@", "]; Restaurant *res = [byID objectForKey:[components objectAtIndex:0]]; if (res) { NSString *resAddress = [components objectAtIndex:3]; NSArray *loc = [NSArray arrayWithObjects:[components objectAtIndex:1], [components objectAtIndex:2]]; [res.locationCoords setObject:loc forKey:resAddress]; } else { NSLog([[components objectAtIndex:0] stringByAppendingString:@" res id not found."]); } } } There are a few weird things happening here. First, at the two lines where the NSArray lines is used, this message is printed to the console- *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFDictionary count]: method sent to an uninitialized mutable dictionary object' which is strange since lines is definitely not an NSMutableDictionary, definitely is initialized, and because the app doesn't crash. Also, at random points in the loop, all of the variables that the debugger can see will become Invalid. Local variables, property variables, everything. Then after a couple lines they will go back to their original values. setObject:forKey never has an effect on res.locationCoords, which is an NSMutableDictionary. I'm sure that res, res.locationCoords, and byId are initialized. I also tried adding a retain or copy to lines, same thing. I'm sure there's a basic memory management principle I'm missing here but I'm at a loss.

    Read the article

  • error writing to plist

    - by Najeebullah Shah
    [array writeToFile:[documentsDirectory stringByAppendingPathComponent:@"data.plist" atomically:YES]; this line gives error that method -stringByAppendingPathComponent not found. whats the issue NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSArray *array = [[NSArray alloc]initWithObjects:@"First", @"Second", @"Third", nil]; [array writeToFile:[documentsDirectory stringByAppendingPathComponent:@"data.plist" atomically:YES]];

    Read the article

  • className method?

    - by fuzzygoat
    I have just been watching the Stanford iPhone lecture online from Jan 2010 and I noticed that the guy from Apple keeps referring to getting an objects class name using "className" e.g. NSArray *myArray = [NSArray arrayWithObjects:@"ONE", @"TWO", nil]; NSLog(@"I am an %@ and have %d items", [myArray className], [myArray count]); However, I can't get this to work, the closest I can come up with it to use class, is className wrong, did it get removed, just curious? NSArray *myArray = [NSArray arrayWithObjects:@"ONE", @"TWO", nil]; NSLog(@"I am an %@ and have %d items", [myArray class], [myArray count]); Gary

    Read the article

  • Clicking the TableView leads you to the another View

    - by lakesh
    I am a newbie to iPhone development. I have already created an UITableView. I have wired everything up and included the delegate and datasource. However, instead of adding a detail view accessory by using UITableViewCellAccessoryDetailClosureButton, I would like to click the UITableViewCell and it should lead to another view with more details about the UITableViewCell. My view controller looks like this: ViewController.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>{ NSArray *tableItems; NSArray *images; } @property (nonatomic,retain) NSArray *tableItems; @property (nonatomic,retain) NSArray *images; @end ViewController.m #import "ViewController.h" #import <QuartzCore/QuartzCore.h> @interface ViewController () @end @implementation ViewController @synthesize tableItems,images; - (void)viewDidLoad { [super viewDidLoad]; tableItems = [[NSArray alloc] initWithObjects:@"Item1",@"Item2",@"Item3",nil]; images = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"clock.png"],[UIImage imageNamed:@"eye.png"],[UIImage imageNamed:@"target.png"],nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return tableItems.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ //Step 1:Check whether if we can reuse a cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; //If there are no new cells to reuse,create a new one if(cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"]; UIView *v = [[UIView alloc] init]; v.backgroundColor = [UIColor redColor]; cell.selectedBackgroundView = v; //changing the radius of the corners //cell.layer.cornerRadius = 10; } //Set the image in the row cell.imageView.image = [images objectAtIndex:indexPath.row]; //Step 3: Set the cell text content cell.textLabel.text = [tableItems objectAtIndex:indexPath.row]; //Step 4: Return the row return cell; } - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ cell.backgroundColor = [ UIColor greenColor]; } @end Need some guidance on this.. Thanks.. Please pardon me if this is a stupid question.

    Read the article

  • iPhone - sorting the results of a core data entity

    - by Digital Robot
    I have a core data entity that represents the attributes of a product, as number, price, etc. The product number is a NSString property and follows the form X.y where X is a number variable of digits and Y is one digit. For example. 132.2, 99.4, etc. I am querying the database to obtain the list of product numbers in order: The code is like this: + (NSArray*)todosOsItens:(NSString *)pName inManagedObjectContext:(NSManagedObjectContext *)context { Product *aProduct = [Product productWithName:pName inManagedObjectContext:context]; NSArray *all = nil; NSFetchRequest *request = [[NSFetchRequest alloc] init]; request.entity = [NSEntityDescription entityForName:@"Attributes" inManagedObjectContext:context]; request.predicate = [NSPredicate predicateWithFormat: @"(belongsTo == %@)", aProduct]; [request setResultType:NSDictionaryResultType]; [request setReturnsDistinctResults:YES]; [request setPropertiesToFetch:[NSArray arrayWithObject:item]]; NSSortDescriptor *sortByItem = [NSSortDescriptor sortDescriptorWithKey:@"ProductNumber" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortByItem]; [request setSortDescriptors:sortDescriptors]; NSError *error = nil; all = [[context executeFetchRequest:request error:&error] mutableCopy]; [request release]; return all; } but this query is not returning the sorted results. The results are coming on their natural order on the database. How do I do that? thanks.

    Read the article

  • How to store array of NSManagedObjects in an NSManagedObject

    - by David Tay
    I am loading my app with a property list of data from a web site. This property list file contains an NSArray of NSDictionaries which itself contains an NSArray of NSDictionaries. Basically, I'm trying to load a tableView of restaurant menu categories each of which contains menu items. My property list file is fine. I am able to load the file and loop through the nodes structure creating NSEntityDescriptions and am able to save to Core Data. Everything works fine and expectedly except that in my menu category managed object, I have an NSArray of menu items for that category. Later on, when I fetch the categories, the pointers to the menu items in a category is lost and I get all the menu items. Am I suppose to be using predicates or does Core Data keep track of my object graph for me? Can anyone look at how I am loading Core Data and point out the flaw in my logic? I'm pretty good with either SQL and OOP by themselves, but am a little bewildered by ORM. I thought that I should just be able to use aggregation in my managed objects and that the framework would keep track of the pointers for me, but apparently not. NSError *error; NSURL *url = [NSURL URLWithString:@"http://foo.com"]; NSArray *categories = [[NSArray alloc] initWithContentsOfURL:url]; NSMutableArray *menuCategories = [[NSMutableArray alloc] init]; for (int i=0; i<[categories count]; i++){ MenuCategory *menuCategory = [NSEntityDescription insertNewObjectForEntityForName:@"MenuCategory" inManagedObjectContext:[self managedObjectContext]]; NSDictionary *category = [categories objectAtIndex:i]; menuCategory.name = [category objectForKey:@"name"]; NSArray *items = [category objectForKey:@"items"]; NSMutableArray *menuItems = [[NSMutableArray alloc] init]; for (int j=0; j<[items count]; j++){ MenuItem *menuItem = [NSEntityDescription insertNewObjectForEntityForName:@"MenuItem" inManagedObjectContext:[self managedObjectContext]]; NSDictionary *item = [items objectAtIndex:j]; menuItem.name = [item objectForKey:@"name"]; menuItem.price = [item objectForKey:@"price"]; menuItem.image = [item objectForKey:@"image"]; menuItem.details = [item objectForKey:@"details"]; [menuItems addObject:menuItem]; } [menuCategory setValue:menuItems forKey:@"menuItems"]; [menuCategories addObject:menuCategory]; [menuItems release]; } if (![[self managedObjectContext] save:&error]) { NSLog(@"An error occurred: %@", [error localizedDescription]); }

    Read the article

  • Programmatically Update UITableView in Response to Button Press

    - by Kyle Begeman
    I have a completely custom view that holds a UITableView and a Custom Tab Bar (basically a UIView that contains 6 UIButtons). I am loading data from a plist file, and then I am sorting the data into multiple arrays based on categories (an array for misc items, and array for mail items, etc.) Each button in the tab bar represents a category, and when I press the button I call the custom function "miscSelected" and so on. How can I have the table view completely reload and then display the tableview based on the array selected (select the misc category and the tableview clears itself and loads the misc array data, same for any other category)? The method I have experimented with is created and NSString named "selection" and then in each button function I set selected to equal whatever section I am selecting. In my cellForRoxAtIndexPath method I have this: if ([self.selection isEqualToString:@"All Items"]) { NSArray *mainDataArray = [NSArray arrayWithContentsOfFile:self.plistFile]; NSSortDescriptor *brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:brandDescriptor]; self.sortedData = [mainDataArray sortedArrayUsingDescriptors:sortDescriptors]; } else if ([self.selection isEqualToString:@"Misc Items"]){ self.sortedData = [NSArray arrayWithContentsOfFile:self.plistFile]; } cell.itemTitle.text = [[self.sortedData objectAtIndex:indexPath.row] objectForKey:@"name"]; For the sake of example and testing I am simply displaying the same data, just one button displays it in alphabetical order and the other does not. This code works only when I start to scroll down and back up, but it does not actually update on button press. Calling myTable reloadData does not do anything either. Any help would be great, thanks!

    Read the article

  • How to hide graph on button click ?

    - by aman-gupta
    Hi, In my application I m using following codes to draw a graph but I want that graph will be displayed on button click :- import @interface frmGraphView : UIView { } @end ///////////////////// // // frmGraphView.m // UV Alarm // // Created by Aman on 4/4/10. // Copyright 2010 MyCompanyName. All rights reserved. // import "frmGraphView.h" @implementation frmGraphView struct TCo_ordinates { float x; float y; }; (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // Initialization code } return self; } /* // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; } */ /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ -(void)drawHGrid { //struct gridForXYaxis *gridForX = (struct gridForX *) calloc(sizeof(struct gridFor)) } (void)drawRect:(CGRect)rect { ifdef _DEBUG NSLog(@"frmGraph_drawRect_start"); endif CGContextRef ctx = UIGraphicsGetCurrentContext(); struct TCo_ordinates *tCoordianates; //creating the object of structure. float fltX1,fltX2,fltY1,fltY2=0; //Dividing the Y-axis ifdef _DEBUG NSLog(@"Start drawing Y-Axis"); endif fltX1 = 25; fltY1 = 2; fltX2 = fltX1; fltY2 = 254; //CGContextSetRGBStrokeColor(ctx, 2.0, 2.0, 2.0, 1.0); CGContextSetLineWidth(ctx, 2.0); CGContextMoveToPoint(ctx, fltX1, fltY1); CGContextAddLineToPoint(ctx, fltX2, fltY2); NSArray *hoursInDays = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12", nil]; NSMutableArray *yAxisCoordinates = [[[NSMutableArray alloc] init] autorelease]; for(int intIndex = 0 ; intIndex < [hoursInDays count] ; fltY2-=20, intIndex++) { ifdef _DEBUG NSLog(@"Start of the partition of y axis"); endif //CGContextSetRGBStrokeColor(ctx, 2, 2, 2, 1); //CGContextSetRGBStrokeColor(ctx, 1.0f/255.0f, 1.0f/255.0f, 1.0f/255.0f, 1.0f); //to draw the black line. CGContextMoveToPoint(ctx, fltX1-3 , fltY2-20); CGContextAddLineToPoint(ctx, fltX1+3, fltY2-20); CGContextSelectFont(ctx, "Helvetica", 12.0, kCGEncodingMacRoman); CGContextSetTextDrawingMode(ctx, kCGTextFill); //CGContextSetRGBFillColor(ctx, 0, 255, 255, 1); CGContextSetStrokeColorWithColor(ctx, [UIColor blueColor].CGColor); CGAffineTransform xform = CGAffineTransformMake( 1.0, 0.0, 0.0, -1.0, 0.0, 0.0); CGContextSetTextMatrix(ctx, xform); const char *arrayDataForYAxis = [[hoursInDays objectAtIndex:intIndex] UTF8String]; CGContextShowTextAtPoint(ctx,fltX1-20 , fltY2-15, arrayDataForYAxis, strlen(arrayDataForYAxis)); CGContextStrokePath(ctx); ifdef _DEBUG NSLog(@"End of the partition of graph"); endif //NSValue *yAxis = [NSValue valueWithCGPoint:CGPointMake((tCoordianates-x = fltX1-21), (tCoordianates-y = fltY2-20))]; // [yAxisCoordinates addObject:yAxis]; ifdef _DEBUG // NSLog(@"The value of yAxisCoordintes: %@", yAxisCoordinates); endif } ifdef _DEBUG NSLog(@"End of drawing Y-Axis"); endif //Dividing the X-axis ifdef _DEBUG NSLog(@"Start drawing X-Axis"); endif fltX1 = 25; fltY1 = 255; fltX2 = 320; fltY2 = fltY1; CGContextMoveToPoint(ctx, fltX1, fltY1); CGContextAddLineToPoint(ctx, fltX2, fltY2); //CGContextSetRGBStrokeColor(ctx, 2, 2, 2, 1); CGContextSetLineWidth(ctx, 2.0); NSArray *weekDays =[[NSArray alloc] initWithObjects:@"Sun", @"Mon", @"Tue", @"Wed", @"Thu", @"Fri", @"Sat", nil]; NSMutableArray *xAxisCoordinates = [[[NSMutableArray alloc] init] autorelease]; for(int intIndex = 0 ; intIndex < [weekDays count] ; fltX1+=40, intIndex++) { //CGContextSetRGBStrokeColor(ctx, 2, 2, 2, 1); //CGContextSetStrokeColorWithColor(ctx, [UIColor orangeColor].CGColor); CGContextMoveToPoint(ctx, fltX1+40 , fltY2-3); CGContextAddLineToPoint(ctx, fltX1+40, fltY2+3); CGContextSelectFont(ctx, "Italic", 12.0, kCGEncodingMacRoman); CGContextSetTextDrawingMode(ctx, kCGTextFill); CGContextSetStrokeColorWithColor(ctx, [UIColor blueColor].CGColor); CGAffineTransform xform = CGAffineTransformMake( 1.0, 0.0, 0.0, -1.0, 0.0, 0.0); CGContextSetTextMatrix(ctx, xform); const char *arrayDataForXAxis = [[weekDays objectAtIndex:intIndex] UTF8String]; CGContextShowTextAtPoint(ctx, fltX1+27, fltY2+20 , arrayDataForXAxis, strlen(arrayDataForXAxis)); CGContextStrokePath(ctx); ifdef _DEBUG NSLog(@"End of drawing X-Axis"); endif //NSValue *xAxis = [NSValue valueWithCGPoint:CGPointMake((tCoordianates->x = fltX1+40), (tCoordianates->y = fltY2+18))]; // [xAxisCoordinates addObject:xAxis]; ifdef _DEBUG //NSLog(@"The value of xAxisCoordintes: %@", xAxisCoordinates); NSLog(@"frmGraph_drawRect_end"); endif } CGContextSetLineWidth(ctx, 10.0); fltX1 = 25; fltY1 = 235; fltX2 = 320; fltY2 = fltY1; NSArray *coordinate1 = [[NSArray alloc] initWithObjects:@"65",@"105",@"145",@"185",@"225",@"265",@"305",nil]; NSArray *coordinate2 = [[NSArray alloc] initWithObjects:@"214",@"174",@"154",@"134",@"114",@"74",@"34",nil]; ifdef _DEBUG NSLog(@"Fuction of Bar_start"); endif for(int intIndex = 0; intIndex < [coordinate1 count], intIndex < [coordinate2 count]; fltX1+=40, intIndex++) { //CGContextSetRGBFillColor(ctx, 0, 0, 245, 1); CGContextMoveToPoint(ctx, fltX1+40, fltY2+19); const char *arrayDataForCoordinate1 = [[coordinate1 objectAtIndex:intIndex] UTF8String]; const char *arrayDataForCoordinate2 = [[coordinate2 objectAtIndex:intIndex] UTF8String]; CGContextAddLineToPoint(ctx, (atof(arrayDataForCoordinate1)), atof(arrayDataForCoordinate2)); } ifdef _DEBUG NSLog(@"Fuction of Bar_end"); endif CGContextClosePath(ctx); CGContextStrokePath(ctx); [hoursInDays release]; [weekDays release]; [coordinate1 release]; [coordinate2 release]; hoursInDays = nil; weekDays = nil; coordinate1 = nil; coordinate2 = nil; } - (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. } (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } (void)dealloc { [super dealloc]; } @end please help me out its urgent

    Read the article

  • Implementation of Nib project to Storyboard, Xcode

    - by Blake Loizides
    I have made a tabbed bar application in storyboard in xcode. I,m new to xcode. I got a Sample TableView XIB project from apple that I edited to my needs,The project has a UITableView that I Customized with Images, And with help of a certain forum member I was able to link up each image to a New View Controller. I tried to port or integrate My Nib Project Code to my StoryBoard Tabbed Bar Application.I thought I had everything right had to comment out a few things to get no errors, But the project only goes to a Blank Table View. Below are 2 links, 1 to my StoryBoard Tabbed Bar Application with the Table Code that I tried to integrate and the other My Successful Nib Project. Also is some code and pictures. If anybody has some free time and does not mind to help I would be extremely grateful for any input given. link1 - Storyboard link2 - XIB DecorsViewController_iPhone.m // // TableViewsViewController.m // TableViews // // Created by Axit Patel on 9/2/10. // Copyright Bayside High School 2010. All rights reserved. // #import "DecorsViewController_iPhone.h" #import "SelectedCellViewController.h" @implementation DecorsViewController_iPhone #pragma mark - Synthesizers @synthesize sitesArray; @synthesize imagesArray; #pragma mark - View lifecycle // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { // Load up the sitesArray with a dummy array : sites NSArray *sites = [[NSArray alloc] initWithObjects:@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", nil]; self.sitesArray = sites; //[sites release]; UIImage *PlumTree = [UIImage imageNamed:@"a.png"]; UIImage *CherryRoyale = [UIImage imageNamed:@"b.png"]; UIImage *MozambiqueWenge = [UIImage imageNamed:@"c.png"]; UIImage *RoyaleMahogany = [UIImage imageNamed:@"d.png"]; UIImage *Laricina = [UIImage imageNamed:@"e.png"]; UIImage *BurntOak = [UIImage imageNamed:@"f.png"]; UIImage *AutrianOak = [UIImage imageNamed:@"g.png"]; UIImage *SilverAcacia = [UIImage imageNamed:@"h.png"]; NSArray *images = [[NSArray alloc] initWithObjects: PlumTree, CherryRoyale, MozambiqueWenge, RoyaleMahogany, Laricina, BurntOak, AutrianOak, SilverAcacia, nil]; self.imagesArray = images; //[images release]; [super viewDidLoad]; } #pragma mark - Table View datasource methods // Required Methods // Return the number of rows in a section - (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section { return [sitesArray count]; } // Returns cell to render for each row - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"CellIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; // Configure cell NSUInteger row = [indexPath row]; // Sets the text for the cell //cell.textLabel.text = [sitesArray objectAtIndex:row]; // Sets the imageview for the cell cell.imageView.image = [imagesArray objectAtIndex:row]; // Sets the accessory for the cell cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; // Sets the detailtext for the cell (subtitle) //cell.detailTextLabel.text = [NSString stringWithFormat:@"This is row: %i", row + 1]; return cell; } // Optional // Returns the number of section in a table view -(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; } #pragma mark - #pragma mark Table View delegate methods // Return the height for each cell -(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 78; } // Sets the title for header in the tableview -(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return @"Decors"; } // Sets the title for footer -(NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { return @"Decors"; } // Sets the indentation for rows -(NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath { return 0; } // Method that gets called from the "Done" button (From the @selector in the line - [viewControllerToShow.navigationItem setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissView)] autorelease]];) - (void)dismissView { [self dismissViewControllerAnimated:YES completion:NULL]; } // This method is run when the user taps the row in the tableview - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; SelectedCellViewController *viewControllerToShow = [[SelectedCellViewController alloc] initWithNibName:@"SelectedCellViewController" bundle:[NSBundle mainBundle]]; [viewControllerToShow setLabelText:[NSString stringWithFormat:@"You selected cell: %d - %@", indexPath.row, [sitesArray objectAtIndex:indexPath.row]]]; [viewControllerToShow setImage:(UIImage *)[imagesArray objectAtIndex:indexPath.row]]; [viewControllerToShow setModalPresentationStyle:UIModalPresentationFormSheet]; [viewControllerToShow setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal]; [viewControllerToShow.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissView)]]; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewControllerToShow]; viewControllerToShow = nil; [self presentViewController:navController animated:YES completion:NULL]; navController = nil; // UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Tapped row!" // message:[NSString stringWithFormat:@"You tapped: %@", [sitesArray objectAtIndex:indexPath.row]] // delegate:nil // cancelButtonTitle:@"Yes, I did!" // otherButtonTitles:nil]; // [alert show]; // [alert release]; } #pragma mark - Memory management - (void)didReceiveMemoryWarning { NSLog(@"Memory Warning!"); [super didReceiveMemoryWarning]; } - (void)viewDidUnload { self.sitesArray = nil; self.imagesArray = nil; [super viewDidUnload]; } //- (void)dealloc { //[sitesArray release]; //[imagesArray release]; // [super dealloc]; //} //@end //- (void)viewDidUnload //{ // [super viewDidUnload]; // Release any retained subviews of the main view. //} - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } else { return YES; } } @end DecorsViewController_iPhone.h #import <UIKit/UIKit.h> @interface DecorsViewController_iPhone : UIViewController <UITableViewDelegate, UITableViewDataSource> { NSArray *sitesArray; NSArray *imagesArray; } @property (nonatomic, retain) NSArray *sitesArray; @property (nonatomic, retain) NSArray *imagesArray; @end SelectedCellViewController.m #import "SelectedCellViewController.h" @implementation SelectedCellViewController @synthesize labelText; @synthesize image; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { } return self; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; [label setText:self.labelText]; [imageView setImage:self.image]; } - (void)viewDidUnload { self.labelText = nil; self.image = nil; // [label release]; // [imageView release]; [super viewDidUnload]; } - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } @end SelectedCellViewController.h @interface SelectedCellViewController : UIViewController { NSString *labelText; UIImage *image; IBOutlet UILabel *label; IBOutlet UIImageView *imageView; } @property (nonatomic, copy) NSString *labelText; @property (nonatomic, retain) UIImage *image; @end

    Read the article

  • plot negative and positive values in same Y-axis in coreplot ios

    - by user3774439
    I have an issue in converting axis labels to int or float values. This is my Y-Axis. It contains temperature values contains -50, 33, 117, 200. CPTXYAxis *y = axisSet.yAxis; y.labelingPolicy = CPTAxisLabelingPolicyNone; y.orthogonalCoordinateDecimal = CPTDecimalFromUnsignedInteger(1); y.majorGridLineStyle = majorGridLineStyle; y.minorGridLineStyle = minorGridLineStyle; y.minorTicksPerInterval = 0.0; y.labelOffset = 0.0; y.title = @""; y.titleOffset = 0.0; NSMutableSet *yLabels = [NSMutableSet setWithCapacity:4]; NSMutableSet *yLocations = [NSMutableSet setWithCapacity:4]; NSArray *yAxisLabels = [NSArray arrayWithObjects:@"-50", @"33", @"117", @"200", nil]; NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init]; [nFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; for ( NSUInteger i = 0; i < [yAxisLabels count]; i++ ) { NSLog(@"%@",[yAxisLabels objectAtIndex:i]); CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:@"%@",[yAxisLabels objectAtIndex:i]] textStyle:axisTextStyle]; label.tickLocation = CPTDecimalFromUnsignedInteger(i); label.offset = y.majorTickLength; if (label) { [yLabels addObject:label]; [yLocations addObject:[NSDecimalNumber numberWithUnsignedInteger:i]]; } label = nil; } y.axisLabels = yLabels; y.majorTickLocations = yLocations; y.labelFormatter = nFormatter; Now, my issue is.. I am getting data from the BLE device as temperature values as strings like 50, 60.3, etc... Now I want plot these values from BLE device with the Y-axis values. i am unable convert these Y-axis labels to temperature values. Could you please help me guys...I have tried many time still no luck. Please help me UPDATE:: This is the way I am creating scatterplot: -(void)createScatterPlotsWithIdentifier:(NSString *)identifier color:(CPTColor *)color forGraph:(CPTGraph *)graph forXYPlotSpace:(CPTXYPlotSpace *)plotSpace{ CPTScatterPlot *scatterPlot = [[CPTScatterPlot alloc] init]; scatterPlot.dataSource = self; scatterPlot.identifier = identifier; //Plot a graph with in the plotspace [plotSpace scaleToFitPlots:[NSArray arrayWithObjects:scatterPlot, nil]]; plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(0) length:CPTDecimalFromUnsignedInteger(30)]; plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromUnsignedInteger(-50) length:CPTDecimalFromUnsignedInteger(250)]; CPTMutablePlotRange *xRange = [[self getCoreplotSpace].xRange mutableCopy]; [xRange expandRangeByFactor:CPTDecimalFromCGFloat(-1)]; [self getCoreplotSpace].xRange = xRange; CPTMutableLineStyle *scatterLineStyle = [scatterPlot.dataLineStyle mutableCopy]; scatterLineStyle.lineWidth = 1; scatterLineStyle.lineColor = color; scatterPlot.dataLineStyle = scatterLineStyle; CPTMutableLineStyle *scatterSymbolLineStyle = [CPTMutableLineStyle lineStyle]; scatterSymbolLineStyle.lineColor = color; CPTPlotSymbol *scatterSymbol = [CPTPlotSymbol ellipsePlotSymbol]; scatterSymbol.fill = [CPTFill fillWithColor:color]; scatterSymbol.lineStyle = scatterSymbolLineStyle; scatterSymbol.size = CGSizeMake(2.0f, 2.0f); scatterPlot.plotSymbol = scatterSymbol; [graph addPlot:scatterPlot toPlotSpace:plotSpace]; } Configuring the Y-axis like this: NSMutableSet *yLabels = [NSMutableSet setWithCapacity:4]; NSMutableSet *yLocations = [NSMutableSet setWithCapacity:4]; NSArray *yAxisLabels = [NSArray arrayWithObjects:@"-50", @"33", @"117", @"200", nil]; NSArray *customTickLocations = [NSArray arrayWithObjects:[NSDecimalNumber numberWithUnsignedInt:-50], [NSDecimalNumber numberWithInt:33], [NSDecimalNumber numberWithInt:117], [NSDecimalNumber numberWithInt:200],nil]; for ( NSUInteger i = 0; i < [yAxisLabels count]; i++ ) { NSLog(@"%@",[yAxisLabels objectAtIndex:i]); CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:@"%@",[yAxisLabels objectAtIndex:i]] textStyle:axisTextStyle]; label.tickLocation = CPTDecimalFromInteger([[customTickLocations objectAtIndex:i] integerValue]); label.offset = y.majorTickLength; if (label) { [yLabels addObject:label]; [yLocations addObject:[NSString stringWithFormat:@"%d",[[customTickLocations objectAtIndex:i] integerValue]]]; } label = nil; } y.axisLabels = yLabels; y.majorTickLocations = [NSSet setWithArray:customTickLocations]; Eric, I set the range as you said in CreateSctterPlot method. But In horizontal line on graph are not coming. Could you please help me what I am wrong. Thanks

    Read the article

  • regular expression to read the string between <title> and </title>

    - by user262325
    Hello every one I hope to read the contents between and in a html string. I think it should be in objective-c @"<title([\\s\\S]*)</title>" below are the codes that rewrited for regular expression //source of NSStringCategory.h #import <Foundation/Foundation.h> #import <regex.h> @interface NSStringCategory:NSObject { regex_t preg; } -(id)initWithPattern:(NSString *)pattern options:(int)options; -(void)dealloc; -(BOOL)matchesString:(NSString *)string; -(NSString *)matchedSubstringOfString:(NSString *)string; -(NSArray *)capturedSubstringsOfString:(NSString *)string; +(NSStringCategory *)regexWithPattern:(NSString *)pattern options:(int)options; +(NSStringCategory *)regexWithPattern:(NSString *)pattern; +(NSString *)null; +(void)initialize; @end @interface NSString (NSStringCategory) -(BOOL)matchedByPattern:(NSString *)pattern options:(int)options; -(BOOL)matchedByPattern:(NSString *)pattern; -(NSString *)substringMatchedByPattern:(NSString *)pattern options:(int)options; -(NSString *)substringMatchedByPattern:(NSString *)pattern; -(NSArray *)substringsCapturedByPattern:(NSString *)pattern options:(int)options; -(NSArray *)substringsCapturedByPattern:(NSString *)pattern; -(NSString *)escapedPattern; @end and .m file #import "NSStringCategory.h" static NSString *nullstring=nil; @implementation NSStringCategory -(id)initWithPattern:(NSString *)pattern options:(int)options { if(self=[super init]) { int err=regcomp(&preg,[pattern UTF8String],options|REG_EXTENDED); if(err) { char errbuf[256]; regerror(err,&preg,errbuf,sizeof(errbuf)); [NSException raise:@"CSRegexException" format:@"Could not compile regex \"%@\": %s",pattern,errbuf]; } } return self; } -(void)dealloc { regfree(&preg); [super dealloc]; } -(BOOL)matchesString:(NSString *)string { if(regexec(&preg,[string UTF8String],0,NULL,0)==0) return YES; return NO; } -(NSString *)matchedSubstringOfString:(NSString *)string { const char *cstr=[string UTF8String]; regmatch_t match; if(regexec(&preg,cstr,1,&match,0)==0) { return [[[NSString alloc] initWithBytes:cstr+match.rm_so length:match.rm_eo-match.rm_so encoding:NSUTF8StringEncoding] autorelease]; } return nil; } -(NSArray *)capturedSubstringsOfString:(NSString *)string { const char *cstr=[string UTF8String]; int num=preg.re_nsub+1; regmatch_t *matches=calloc(sizeof(regmatch_t),num); if(regexec(&preg,cstr,num,matches,0)==0) { NSMutableArray *array=[NSMutableArray arrayWithCapacity:num]; int i; for(i=0;i<num;i++) { NSString *str; if(matches[i].rm_so==-1&&matches[i].rm_eo==-1) str=nullstring; else str=[[[NSString alloc] initWithBytes:cstr+matches[i].rm_so length:matches[i].rm_eo-matches[i].rm_so encoding:NSUTF8StringEncoding] autorelease]; [array addObject:str]; } free(matches); return [NSArray arrayWithArray:array]; } free(matches); return nil; } +(NSStringCategory *)regexWithPattern:(NSString *)pattern options:(int)options { return [[[NSStringCategory alloc] initWithPattern:pattern options:options] autorelease]; } +(NSStringCategory *)regexWithPattern:(NSString *)pattern { return [[[NSStringCategory alloc] initWithPattern:pattern options:0] autorelease]; } +(NSString *)null { return nullstring; } +(void)initialize { if(!nullstring) nullstring=[[NSString alloc] initWithString:@""]; } @end @implementation NSString (NSStringCategory) -(BOOL)matchedByPattern:(NSString *)pattern options:(int)options { NSStringCategory *re=[NSStringCategory regexWithPattern:pattern options:options|REG_NOSUB]; return [re matchesString:self]; } -(BOOL)matchedByPattern:(NSString *)pattern { return [self matchedByPattern:pattern options:0]; } -(NSString *)substringMatchedByPattern:(NSString *)pattern options:(int)options { NSStringCategory *re=[NSStringCategory regexWithPattern:pattern options:options]; return [re matchedSubstringOfString:self]; } -(NSString *)substringMatchedByPattern:(NSString *)pattern { return [self substringMatchedByPattern:pattern options:0]; } -(NSArray *)substringsCapturedByPattern:(NSString *)pattern options:(int)options { NSStringCategory *re=[NSStringCategory regexWithPattern:pattern options:options]; return [re capturedSubstringsOfString:self]; } -(NSArray *)substringsCapturedByPattern:(NSString *)pattern { return [self substringsCapturedByPattern:pattern options:0]; } -(NSString *)escapedPattern { int len=[self length]; NSMutableString *escaped=[NSMutableString stringWithCapacity:len]; for(int i=0;i<len;i++) { unichar c=[self characterAtIndex:i]; if(c=='^'||c=='.'||c=='['||c=='$'||c=='('||c==')' ||c=='|'||c=='*'||c=='+'||c=='?'||c=='{'||c=='\\') [escaped appendFormat:@"\\%C",c]; else [escaped appendFormat:@"%C",c]; } return [NSString stringWithString:escaped]; } @end I use the codes below to get the string between "" and "" NSStringCategory *a=[[NSStringCategory alloc] initWithPattern:@"<title([\s\S]*)</title>" options:0];// Unfortunately [a matchedSubstringOfString:response]] always returns nil I do not if the regular expression is wrong or any other reason. Welcome any comment Thanks interdev

    Read the article

  • NSFetchedResultsController: using of NSManagedObjectContext during update brings to crash

    - by Kentzo
    Here is the interface of my controller class: @interface ProjectListViewController : UITableViewController <NSFetchedResultsControllerDelegate> { NSFetchedResultsController *fetchedResultsController; NSManagedObjectContext *managedObjectContext; } @end I use following code to init fetchedResultsController: if (fetchedResultsController != nil) { return fetchedResultsController; } // Create and configure a fetch request with the Project entity. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // Create the sort descriptors array. NSSortDescriptor *projectIdDescriptor = [[NSSortDescriptor alloc] initWithKey:@"projectId" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:projectIdDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Create and initialize the fetch results controller. NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil]; self.fetchedResultsController = aFetchedResultsController; fetchedResultsController.delegate = self; As you can see, I am using the same managedObjectContext as defined in my controller class Here is an adoption of the NSFetchedResultsControllerDelegate protocol: - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { // The fetch controller is about to start sending change notifications, so prepare the table view for updates. [self.tableView beginUpdates]; } - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { UITableView *tableView = self.tableView; switch(type) { case NSFetchedResultsChangeInsert: [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeUpdate: [self _configureCell:(TDBadgedCell *)[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; break; case NSFetchedResultsChangeMove: if (newIndexPath != nil) { [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; } else { [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade]; } break; } } - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { switch(type) { case NSFetchedResultsChangeInsert: [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; case NSFetchedResultsChangeDelete: [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.tableView endUpdates]; } Inside of the _configureCell:atIndexPath: method I have following code: NSFetchRequest *issuesNumberRequest = [NSFetchRequest new]; NSEntityDescription *issueEntity = [NSEntityDescription entityForName:@"Issue" inManagedObjectContext:managedObjectContext]; [issuesNumberRequest setEntity:issueEntity]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"projectId == %@", project.projectId]; [issuesNumberRequest setPredicate:predicate]; NSUInteger issuesNumber = [managedObjectContext countForFetchRequest:issuesNumberRequest error:nil]; [issuesNumberRequest release]; I am using the managedObjectContext again. But when I am trying to insert new Project, app crashes with following exception: Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-984.38/UITableView.m:774 Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (4) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted).' Fortunately, I've found a workaround: if I create and use separate NSManagedObjectContext inside of the _configureCell:atIndexPath: method app won't crash! I only want to know, is this behavior correct or not?

    Read the article

  • CoreData, transient atribute and EXC_BAD_ACCESS.

    - by Lukasz
    I'm trying to build simple file browser and i'm stuck. I defined classes, build window, add controllers, views.. Everything works but only ONE time. Selecting again Folder in NSTableView or trying to get data from Folder.files causing silent EXC_BAD_ACCESS (code=13, address0x0) from main. Info about files i keep outside of CoreData, in simple class, I don't want to save them: #import <Foundation/Foundation.h> @interface TPDrawersFileInfo : NSObject @property (nonatomic, retain) NSString * filename; @property (nonatomic, retain) NSString * extension; @property (nonatomic, retain) NSDate * creation; @property (nonatomic, retain) NSDate * modified; @property (nonatomic, retain) NSNumber * isFile; @property (nonatomic, retain) NSNumber * size; @property (nonatomic, retain) NSNumber * label; +(TPDrawersFileInfo *) initWithURL: (NSURL *) url; @end @implementation TPDrawersFileInfo +(TPDrawersFileInfo *) initWithURL: (NSURL *) url { TPDrawersFileInfo * new = [[TPDrawersFileInfo alloc] init]; if (new!=nil) { NSFileManager * fileManager = [NSFileManager defaultManager]; NSError * error; NSDictionary * infoDict = [fileManager attributesOfItemAtPath: [url path] error:&error]; id labelValue = nil; [url getResourceValue:&labelValue forKey:NSURLLabelNumberKey error:&error]; new.label = labelValue; new.size = [infoDict objectForKey: @"NSFileSize"]; new.modified = [infoDict objectForKey: @"NSFileModificationDate"]; new.creation = [infoDict objectForKey: @"NSFileCreationDate"]; new.isFile = [NSNumber numberWithBool:[[infoDict objectForKey:@"NSFileType"] isEqualToString:@"NSFileTypeRegular"]]; new.extension = [url pathExtension]; new.filename = [[url lastPathComponent] stringByDeletingPathExtension]; } return new; } Next I have class Folder, which is NSManagesObject subclass // Managed Object class to keep info about folder content @interface Folder : NSManagedObject { NSArray * _files; } @property (nonatomic, retain) NSArray * files; // Array with TPDrawersFileInfo objects @property (nonatomic, retain) NSString * url; // url of folder -(void) reload; //if url changed, load file info again. @end @implementation Folder @synthesize files = _files; @dynamic url; -(void)awakeFromInsert { [self addObserver:self forKeyPath:@"url" options:NSKeyValueObservingOptionNew context:@"url"]; } -(void)awakeFromFetch { [self addObserver:self forKeyPath:@"url" options:NSKeyValueObservingOptionNew context:@"url"]; } -(void)prepareForDeletion { [self removeObserver:self forKeyPath:@"url"]; } -(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (context == @"url") { [self reload]; } } -(void) reload { NSMutableArray * result = [NSMutableArray array]; NSError * error = nil; NSFileManager * fileManager = [NSFileManager defaultManager]; NSString * percented = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSArray * listDir = [fileManager contentsOfDirectoryAtURL: [NSURL URLWithString: percented] includingPropertiesForKeys: [NSArray arrayWithObject: NSURLCreationDateKey ] options:NSDirectoryEnumerationSkipsHiddenFiles error:&error]; if (error!=nil) {NSLog(@"Error <%@> reading <%@> content", error, self.url);} for (id fileURL in listDir) { TPDrawersFileInfo * fi = [TPDrawersFileInfo initWithURL:fileURL]; [result addObject: fi]; } _files = [NSArray arrayWithArray:result]; } @end In app delegate i defined @interface TPAppDelegate : NSObject <NSApplicationDelegate> { IBOutlet NSArrayController * foldersController; Folder * currentFolder; } - (IBAction)chooseDirectory:(id)sender; // choose folder and - (Folder * ) getFolderObjectForPath: path { //gives Folder object if already exist or nil if not ..... } - (IBAction)chooseDirectory:(id)sender { //Opens panel, asking for url NSOpenPanel * panel = [NSOpenPanel openPanel]; [panel setCanChooseDirectories:YES]; [panel setCanChooseFiles:NO]; [panel setMessage:@"Choose folder to show:"]; NSURL * currentDirectory; if ([panel runModal] == NSOKButton) { currentDirectory = [[panel URLs] objectAtIndex:0]; } Folder * folderObject = [self getFolderObjectForPath:[currentDirectory path]]; if (folderObject) { //if exist: currentFolder = folderObject; } else { // create new one Folder * newFolder = [NSEntityDescription insertNewObjectForEntityForName:@"Folder" inManagedObjectContext:self.managedObjectContext]; [newFolder setValue:[currentDirectory path] forKey:@"url"]; [foldersController addObject:newFolder]; currentFolder = newFolder; } [foldersController setSelectedObjects:[NSArray arrayWithObject:currentFolder]]; } Please help ;)

    Read the article

  • NSPredicate problem with fetchedResultsController

    - by RyJ
    Please help! I've been trying to figure this out for way too long. I can't seem to use an NSPredicate in my fetchedResultsController method: - (NSFetchedResultsController *)fetchedResultsController { if (fetchedResultsController != nil) return fetchedResultsController; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Tweet" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSPredicate *predicate = [NSPredicate predicateWithFormat: @"column == 0"]; [fetchRequest setPredicate:predicate]; [fetchRequest setReturnsObjectsAsFaults:NO]; [fetchRequest setFetchBatchSize:20]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"created_at" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; aFetchedResultsController.delegate = self; self.fetchedResultsController = aFetchedResultsController; [aFetchedResultsController release]; [fetchRequest release]; [sortDescriptor release]; [sortDescriptors release]; return fetchedResultsController; } Yet, in another method, where I simply check to see if an object exists, the predicate works like a charm: - (BOOL)findObjectWithKey:(NSString *)key andValue:(NSString *)value sortBy:(NSString *)sort { NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Tweet" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; NSPredicate *predicate = [NSPredicate predicateWithFormat: @"%K == %@", key, value]; [request setPredicate:predicate]; [request setReturnsObjectsAsFaults:NO]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sort ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; aFetchedResultsController.delegate = self; NSError *error = nil; NSArray *result = [managedObjectContext executeFetchRequest:request error:&error]; [aFetchedResultsController release]; [request release]; [sortDescriptor release]; [sortDescriptors release]; if ((result != nil) && ([result count]) && (error == nil)) { return TRUE; } else { return FALSE; }} What am I doing wrong? Thanks in advance!

    Read the article

  • Iphone App crashing on launch

    - by Declan Scott
    Hey, My simple iphone app is crashing on launch, it says "the application downloadText quit unexcpectedly i none of these windows that pop up when a mac app crashes and has a send to Apple button. My .h is below and i would greatly appreciate it if anyone could give me a hand as to what's wrong? thanks, Declan `#import "downloadTextViewController.h" @implementation downloadTextViewController // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { NSString *myPath = [self saveFilePath]; NSLog(myPath); BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath]; if (fileExists) { NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath]; textView.text = [values objectAtIndex:0]; [values release]; } // notification UIApplication *myApp = [UIApplication sharedApplication]; // add yourself to the dispatch table [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:myApp]; [super viewDidLoad]; } (IBAction)fetchData { /// Show activityIndicator / progressView NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://simpsonatyapps.com/exampletext.txt"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1.0]; NSURLConnection *downloadConnection = [[NSURLConnection alloc] initWithRequest:downloadRequest delegate:self]; if (downloadConnection) downloadedData = [[NSMutableData data] retain]; else { /// Error message } } (void)connection:(NSURLConnection *)downloadConnection didReceiveData:(NSData *)data { [downloadedData appendData:data]; NSString *file = [[NSString alloc] initWithData:downloadedData encoding:NSUTF8StringEncoding]; textView.text = file; /// Remove activityIndicator / progressView [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1]; } (NSString *) saveFilePath { NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); return [[pathArray objectAtIndex:0] stringByAppendingPathComponent:@"savedddata.plist"]; } (void)applicationWillTerminate:(UIApplication *)application { NSArray *values = [[NSArray alloc] initWithObjects:textView.text,nil]; [values writeToFile:[self saveFilePath] atomically:YES]; [values release]; } (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. } (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } (void)dealloc { [super dealloc]; } (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { return nil; } @end `

    Read the article

  • How to handle float values in a plist

    - by Banjer
    I'm reading in a plist from a web server, generated with some php. When I read that into an NSArray in my iphone app, and then spit the NSArray out with NSLog to check it out, I see that the float values are treated as strings. I would like the "distance" values to be treated as numeric and not strings. This plist is displayed in a table view where it can be sorted by distance, but the problem is is distance is sorted as a string, so I get some funny sorting results. Can I convert the distance values to float from string in the NSArray? Or maybe theres a simpler solution like tweaking the plist definition, or maybe something in the NSMutableURLRequest code? My plist looks like this: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <dict> <key>name</key> <string>Pizza Joint</string> <key>distance</key> <string>2.1</string> </dict> <dict> <key>name</key> <string>Burger Kang</string> <key>distance</key> <string>5</string> </dict> </array> </plist> After reading it into an NSArray, it looks like this per NSLog: result: ( { distance = "2.1"; name = "Pizza Joint"; }, { distance = 5; name = "Burger Kang"; } ) Here is the Objective-C code that retrieves the plist: // Set up url request // postData and postLength are left out, but I can post in this question if needed. NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:@"http://mysite.com/get_plist.php"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSError *error; NSURLResponse *response; NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString *string = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]; // libraryContent is an NSArray self.libraryContent = [string propertyList]; NSLog(@"result: %@", self.libraryContent);

    Read the article

  • Cocoa XML reader app

    - by Miskia
    Hello, I'm a newbie to Cocoa, just develop some little apps with C/C++ on Windows. I want to make a "simple" app on Cocoa. When the user specific XML file, the file nodes are represented "enduser viewable". I made an interface with some NSTextField. I made a subclass of NSDocument called "XMLFile" so i got "XMLFile.h" and "XMLFile.m" in my Xcode project. In the plist of my app i setup a new "Document Types": XML File - extensions: xml - role: view - class: XMLFile - store type: XML Here is my "XMLFile.h": #import <Cocoa/Cocoa.h> @interface FichierXML : NSDocument { } IBOutlet NSTextField *dateField; IBOutlet NSTextField *titleField; IBOutlet NSTextField *descField; IBOutlet NSTextField *vidfileField; IBOutlet NSTextField *imgfileField; IBOutlet NSObjectController *object; NSUInteger *mask; @end And here is my "XMLFile.m": #import "XMLFile.h" @implementation XMLFile - (BOOL)readFromData:(NSData *)datafile ofType:(NSString *)typeName error:(NSError **)outerror { NSMutableArray* ReportCreationDate = [[NSMutableArray alloc] initWithCapacity:10]; NSMutableArray* ReportTitle = [[NSMutableArray alloc] initWithCapacity:10]; NSMutableArray* ReportDescription = [[NSMutableArray alloc] initWithCapacity:10]; NSMutableArray* VideoPath = [[NSMutableArray alloc] initWithCapacity:10]; NSMutableArray* VideoThumbnailImageName = [[NSMutableArray alloc] initWithCapacity:10]; NSXMLDocument* doc = [[NSXMLDocument alloc] initWithData:datafile options:mask error:outerror]; NSXMLElement* root = [doc rootElement]; NSArray* dateElement = [root nodesForXPath:@"//Report/ReportCreationDate" error:nil]; for(NSXMLElement* xmlElement in dateElement) [dateElement setStringValue:[xmlElement stringValue]]; NSArray* titleElement = [root nodesForXPath:@"//Report/ReportTitle" error:nil]; for(NSXMLElement* xmlElement in titleElement) [titleField setStringValue:[xmlElement stringValue]]; NSArray* descElement = [root nodesForXPath:@"//Report/ReportDescription" error:nil]; for(NSXMLElement* xmlElement in descElement) [descField setStringValue:[xmlElement stringValue]]; NSArray* vidfileElement = [root nodesForXPath:@"//Report/Videos/Video/VideoPath" error:nil]; for(NSXMLElement* xmlElement in vidfileElement) [vidfileField setStringValue:[xmlElement stringValue]]; NSArray* imgfileElement = [root nodesForXPath:@"//Report/Videos/Video/VideoThumbnailImageName" error:nil]; for(NSXMLElement* xmlElement in imgfileElement) [imgfileField setStringValue:[xmlElement stringValue]]; [doc release]; [ReportCreationDate release]; [ReportTitle release]; [ReportDescription release]; [VideoPath release]; [VideoThumbnailImageName release]; return YES; } @end So. The user open the XMLFile, and XMLDocument analyse the file to extract nodes' data and send it to the differents NSTextField... But it doesn't work :( If someone can help me... I'm a newbie so don't be too rude if I made big mistakes :) Miskia.

    Read the article

  • Cocoa NSStream works with SSL, with socks5, but not at the same time

    - by Evan D
    Upon connecting (to an FTP, at first without SSL) I run: NSArray *objects = [NSArray arrayWithObjects:@"proxy.ip", [NSNumber numberWithInt:1080], NSStreamSOCKSProxyVersion5, @"user", @"pass", nil]; NSArray *keys = [NSArray arrayWithObjects:NSStreamSOCKSProxyHostKey, NSStreamSOCKSProxyPortKey, NSStreamSOCKSProxyVersionKey, NSStreamSOCKSProxyUserKey, NSStreamSOCKSProxyPasswordKey, nil]; NSDictionary *proxyDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; [iStream retain]; [iStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [iStream setProperty:proxyDictionary forKey:NSStreamSOCKSProxyConfigurationKey]; [iStream open]; same for iStream. This allows me to connect succesfully through a socks5 proxy. If I continue without setProperty:proxyDictionary... (socks5 disabled) I would tell the server to switch to SSL, and then successfully apply these settings to the in/output streams, thus giving me a SSL connection: NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:1]; [settings setObject:(NSString *)NSStreamSocketSecurityLevelTLSv1 forKey:(NSString *)kCFStreamSSLLevel]; // to allow selfsigned certificates: [settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot]; [iStream retain]; [iStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; CFReadStreamSetProperty((CFReadStreamRef)iStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings); [iStream setProperty:NSStreamSocketSecurityLevelTLSv1 forKey:NSStreamSocketSecurityLevelKey]; same for oStream. All of which works fine if I disable socks5. If I turn it on (line 7 in the first snippit) I lose contact when applying the SSL settings. If I had to guess, I'd think it's losing some properties when applying (ssl) "settings"? Please help :) Evan

    Read the article

  • populate UITableView from json

    - by mcgrailm
    Hello all working on my building my first iDevice app and I am trying to populate a UITableView with data from json result I can get it to load from plist array no propblem and I can even see my json the problem I'm having is that the UITableView never gets to see the json results please bare with me as this is first time with obj-c or anything like it in my .h file @interface TableViewViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> { NSArray *exercises; NSMutableData *responseData; } in my .m file - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return exercises.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //create a cell UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; // fill it with contnets cell.textLabel.text = [exercises objectAtIndex:indexPath.row]; // return it return cell; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { responseData = [[NSMutableData data] retain]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://url_to_json"]]; [[NSURLConnection alloc] initWithRequest:request delegate:self ]; // load from plist //NSString *myfile = [[NSBundle mainBundle] pathForResource:@"exercise" ofType:@"plist"]; //exercises = [[NSArray alloc] initWithContentsOfFile:myfile]; [super viewDidLoad]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [responseData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [responseData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"Connection failed: %@", [error description]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [connection release]; NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; [responseData release]; NSDictionary *dictionary = [responseString JSONValue]; NSArray *response = [dictionary objectForKey:@"response"]; exercises = [[NSArray alloc] initWithArray:response]; }

    Read the article

  • NSMutableArray of Objects

    - by Terry Owen
    First off I am very new to Objective C and iPhone programming. Now that that is out of the way. I have read through most of the Apple documentation on this and some third party manuals. I guess I just want to know if I'm going about this the correct way ... - (NSMutableArray *)makeModel { NSString *api = @"http://www.mycoolnewssite.com/api/v1"; NSArray *namesArray = [NSArray arrayWithObjects:@"News", @"Sports", @"Entertainment", @"Business", @"Features", nil]; NSArray *urlsArray = [NSArray arrayWithObjects: [NSString stringWithFormat:@"%@/news/news/25/stories.json", api], [NSString stringWithFormat:@"%@/news/sports/25/stories.json", api], [NSString stringWithFormat:@"%@/news/entertainment/25/stories.json", api], [NSString stringWithFormat:@"%@/news/business/25/stories.json", api], [NSString stringWithFormat:@"%@/news/features/25/stories.json", api], nil]; NSMutableArray *result = [NSMutableArray array]; for (int i = 0; i < [namesArray count]; i++) { NSMutableDictionary *objectDict = [NSMutableDictionary dictionary]; NSString *name = (NSString *)[namesArray objectAtIndex:i]; NSString *url = (NSString *)[urlsArray objectAtIndex:i]; [objectDict setObject:name forKey:@"NAME"]; [objectDict setObject:url forKey:@"URL"]; [objectDict setObject:@"NO" forKey:@"HASSTORIES"]; [result addObject:objectDict]; } return result; } Any insight would be appreciated ;-)

    Read the article

  • iphone reload tableView

    - by Brodie4598
    In the following code, I have determined that everything works, up until [tableView reloadData] i have NSLOGs set up in the table view delegate methods and none of them are getting called. I have other methods doing the same reloadData and it works perfectly. The only difference tha I am awayre of is tha this is in a @catch block. maybe you smart guys can see something i'm doing wrong... @catch (NSException * e) {////chart is user genrated logoView.image = nil; NSInteger row = [picker selectedRowInComponent:0]; NSString *selectedAircraft = [aircraft objectAtIndex:row]; NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsPath = [paths objectAtIndex:0]; NSString *checklistPath = [[NSString alloc]initWithFormat:@"%@/%@.checklist",docsPath,selectedAircraft]; NSString *dataString = [NSString stringWithContentsOfFile:checklistPath encoding: NSUTF8StringEncoding error:NULL]; if ([dataString hasPrefix:@"\n"]) { dataString = [dataString substringFromIndex:1]; } NSArray *tempArray = [dataString componentsSeparatedByString:@"\n"]; NSDictionary *temporaryDictionary = [NSDictionary dictionaryWithObject: tempArray forKey:@"User Generated Checklist"]; self.names = temporaryDictionary; NSArray *tempArray2 = [NSArray arrayWithObject:@"01User Generated Checklist"]; self.keys = tempArray2; aircraftLabel.text = selectedAircraft; checklistSelectPanel.hidden = YES; [tableView reloadData]; }

    Read the article

  • Animation not playing

    - by Tate Allen
    Hello again, I didn't say this last time but I am relatively new to iPhone programming and extremely new to iPhone game development so bear with me. In my game, when I tilt the device, the character moves and faces the correct direction, but does not animate. I am using an animated UIImageView. Here is the code: float newX = character.center.x + (accel.x * 12); if (newX 30 && newX < 290) character.center = CGPointMake(newX, character.center.y); if (accel.x < 0) { NSArray *imgArray = [[NSArray alloc] initWithObjects: [UIImage imageNamed:@"run3left.png"], [UIImage imageNamed:@"run1left.png"], [UIImage imageNamed:@"run2left.png"], [UIImage imageNamed:@"run1left.png"], nil]; character.animationImages = imgArray; character.animationDuration = 0.5; character.contentMode = UIViewContentModeBottomLeft; [self.view addSubview:character]; [character startAnimating]; } if (accel.x > 0) { NSArray *imgArray = [[NSArray alloc] initWithObjects: [UIImage imageNamed:@"run3.png"], [UIImage imageNamed:@"run1.png"], [UIImage imageNamed:@"run2.png"], [UIImage imageNamed:@"run1.png"], nil]; character.animationImages = imgArray; character.animationDuration = 0.5; character.contentMode = UIViewContentModeBottomLeft; [self.view addSubview:character]; [character startAnimating]; } }

    Read the article

  • Core Data @sum aggregate

    - by nasim
    I am getting an exception when I try to get @sum on a column in iPhone Core-Data application. My two models are following - Task model: @interface Task : NSManagedObject { } @property (nonatomic, retain) NSString * taskName; @property (nonatomic, retain) NSSet* completion; @end @interface Task (CoreDataGeneratedAccessors) - (void)addCompletionObject:(NSManagedObject *)value; - (void)removeCompletionObject:(NSManagedObject *)value; - (void)addCompletion:(NSSet *)value; - (void)removeCompletion:(NSSet *)value; @end Completion model: @interface Completion : NSManagedObject { } @property (nonatomic, retain) NSNumber * percentage; @property (nonatomic, retain) NSDate * time; @property (nonatomic, retain) Task * task; @end And here is the fetch: NSFetchRequest *request = [[NSFetchRequest alloc] init]; request.entity = [NSEntityDescription entityForName:@"Task" inManagedObjectContext:context]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"taskName" ascending:YES]; request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; NSError *error; NSArray *results = [context executeFetchRequest:request error:&error]; NSArray *parents = [results valueForKeyPath:@"taskName"]; NSArray *children = [results valueForKeyPath:@"[email protected]"]; NSLog(@"%@ %@", parents, children); [request release]; [sortDescriptor release]; The exception is thrown at the fourth line from bottom. The thrown exception is: *** -[NSCFSet decimalValue]: unrecognized selector sent to instance 0x3b25a30 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFSet decimalValue]: unrecognized selector sent to instance 0x3b25a30' I would very much appreciate any kind of help. Thanks.

    Read the article

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