Search Results

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

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

  • Why I got a "sent to freed object error"?

    - by Tattat
    I have a Table View, and CharTableController, the CharTableController works like this: .h: #import <Foundation/Foundation.h> @interface CharTableController : UITableViewController <UITableViewDelegate, UITableViewDataSource>{ // IBOutlet UILabel *debugLabel; NSArray *listData; } //@property (nonatomic, retain) IBOutlet UILabel *debugLabel; @property (nonatomic, retain) NSArray *listData; @end The .m: #import "CharTableController.h" @implementation CharTableController @synthesize listData; - (void)viewDidLoad { NSArray *array = [[NSArray alloc] initWithObjects:@"Sleepy", @"Sneezy", @"Bashful", @"Happy", @"Doc", @"Grumpy", @"Dopey", @"Thorin", @"Dorin", @"Nori", @"Ori", @"Balin", @"Dwalin", @"Fili", @"Kili", @"Oin", @"Gloin", @"Bifur", @"Bofur", @"Bombur", nil]; self.listData = array; [array release]; [super viewDidLoad]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.listData count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease]; NSUInteger row = [indexPath row]; cell.textLabel.text = [listData objectAtIndex:row]; } return cell; } @end And I Use the IB to link the TableView's dataSource and delegate to the CharTableController. In the CharTableController's view is the TableView in IB obviously. Reference Object in dataSource TableView and delegate TableView. What's wrong with my setting? thz.

    Read the article

  • iPhone: Creating a hierarchy-based table navigation.

    - by Jack Griffiths
    Hi there, I've tried to ask this before, but nothing got answered. Basically, I would like someone to explain to me how to create a table, which when a cell is tapped, pushes the user to the next view for that cell. I have this so far: Click here to view what I have. I would further like to, say when CSS is tapped, it goes to a new view which has another table in it. This table would then take the user to a detail view, which is scrollable and you can switch pages through it. I would appreciate longer, more structured tutorials on how to do each and every bit to get it to work. Here's my array in my implementation file: - (void)viewDidLoad { arryClientSide = [[NSArray alloc] initWithObjects:@"CSS", @"HTML", @"JavaScript", @"XML", nil]; arryServerSide = [[NSArray alloc] initWithObjects:@"Apache", @"PHP", @"SQL", nil]; self.title = @"Select a Language"; [super viewDidLoad]; } and my .h: @interface RootViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> { IBOutlet UITableView *tblSimpleTable; NSArray *arryClientSide; NSArray *arryServerSide; } My current code crashes the script, and this error is returned in the console: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableViewController loadView] loaded the "NextView" nib but didn't get a UITableView.' If that error is the source of why it's not pushing, then an explanation of how to remedy that would also be appreciated Many thanks, Jack

    Read the article

  • How to assign a table view controller to a table view on iPhone?

    - by Tattat
    I have a CharTableController, View and TableView on my IB. The CharTableController is using "CharTableController" in class identity. And this is how I implemented in the .h, and I want use the "CharTableController" to control the table only: @interface CharTableController : UITableViewController <UITableViewDelegate, UITableViewDataSource>{ // IBOutlet UILabel *debugLabel; NSArray *listData; } //@property (nonatomic, retain) IBOutlet UILabel *debugLabel; @property (nonatomic, retain) NSArray *listData; @end It is the .m: #import "CharTableController.h" @implementation CharTableController @synthesize listData; - (void)viewDidLoad { //NSLog(@"bulll"); // [debugLabel setText:@"success"]; NSArray *array = [[NSArray alloc] initWithObjects:@"A", @"B", @"C", @"D", @"E", nil]; self.listData = array; [array release]; [super viewDidLoad]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.listData count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease]; NSUInteger row = [indexPath row]; cell.textLabel.text = [listData objectAtIndex:row]; } return cell; } @end In the IB, I already assign the CharTableController's view to Table View in IB. And Table View is under the View, in IB. After I run the program, I can see the table view, but I can't see any char in the table view, why? What's wrong with my code? thz.

    Read the article

  • Behavior difference between UIView.subviews and [NSView subviews]

    - by zpasternack
    I have a piece of code in an iPhone app, which removes all subviews from a UIView subclass. It looks like this: NSArray* subViews = self.subviews; for( UIView *aView in subViews ) { [aView removeFromSuperview]; } This works fine. In fact, I never really gave it much thought until I tried nearly the same thing in a Mac OS X app (from an NSView subclass): NSArray* subViews = [self subviews]; for( NSView *aView in subViews ) { [aView removeFromSuperview]; } That totally doesn’t work. Specifically, at runtime, I get this: *** Collection <NSCFArray: 0x1005208a0> was mutated while being enumerated. I ended up doing it like so: NSArray* subViews = [[self subviews] copy]; for( NSView *aView in subViews ) { [aView removeFromSuperview]; } [subViews release]; That's fine. What’s bugging me, though, is why does it work on the iPhone? subviews is a copy property: @property(nonatomic,readonly,copy) NSArray *subviews; My first thought was, maybe @synthesize’d getters return a copy when the copy attribute is specified. The doc is clear on the semantics of copy for setters, but doesn’t appear to say either way for getters (or at least, it’s not apparent to me). And actually, doing a few tests of my own, this clearly does not seem to be the case. Which is good, I think returning a copy would be problematic, for a few reasons. So the question is: how does the above code work on the iPhone? NSView is clearly returning a pointer to the actual array of subviews, and perhaps UIView isn’t. Perhaps it’s simply an implementation detail of UIView, and I shouldn’t get worked up about it. Can anyone offer any insight?

    Read the article

  • Custom Header in ASIHTTPREQUEST

    - by Sharon Nathaniel
    Here is my problem. I am using ASIHTTPREQUEST to send request and get response. Now my need of the time is to upload a image,audio , video or docs via PUT method with a custom header . The header takes filename , filesize,sha256sum,username,mediatype,resume as parameters. Here is the code how I am doing that . -(void)uploadFile { NSString *resume =@"0"; NSUserDefaults *userCredentials =[NSUserDefaults standardUserDefaults]; NSString *userName =[userCredentials objectForKey:@"userName"]; NSArray *objects =[NSArray arrayWithObjects:selectedMediaType,delegate.fileName,userName,fileSize,fileSHA256Sum,resume, nil]; NSArray *keys =[NSArray arrayWithObjects:@"mediatype",@"file_name",@"usrname",@"filesize",@"sha256sum",@"resume", nil]; discSentValue =[NSDictionary dictionaryWithObjects:objects forKeys:keys]; NSURL *url = [NSURL URLWithString:@"http://briareos.code20.com/putmedia.php"]; uploadMedia = [ASIFormDataRequest requestWithURL:url]; [uploadMedia addRequestHeader:@"MEDIA_UPLOAD_CUSTOM_HEADER" value:[discSentValue JSONRepresentation]]; [uploadMedia setData:dataToUpload forKey:@"File"]; [uploadMedia setDelegate:self]; [uploadMedia setRequestMethod:@"PUT"]; [uploadMedia startAsynchronous]; } But the server is unable to recognize the header , it always returns "invalid header"

    Read the article

  • Disable ARC with Xcode 5

    - by user2187565
    First, sorry for my bad english, I'm french and had 15years old but StackOverFlow is for me the best forum for developers. So, in the previous versions of Xcode, we can disable ARC (Automatic Reference Counting) in the project settings when we create the project. Not now with Xcode 5 and ARC to pose me a problem: with an property list file, for the reading step, Xcode send me an error: "implicit conversion of 'int' to 'id' is disallowed with ARC". I had not the problem with the same code with Xcode 4. In my property list file, The keys are numbers and also in my viewController.m . NIKOS M.: No problem, but I don't see how I can add compiler flag with the 5th version of Xcode. The code (with french string...): NSString *error; NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [rootPath stringByAppendingPathComponent:@"Save.plist"]; NSArray *keys = [NSArray arrayWithObjects:@"valeurCompteur1", @"valeurCompteur2", @"valeurCompteur3", @"valeurCompteur4", @"valeurCompteur5", @"nomCompteur1", @"nomCompteur2", @"nomCompteur3", @"nomCompteur4", @"nomCompteur5", nil]; NSArray *objs = [NSArray arrayWithObjects: compteur1, compteur2, compteur3, compteur4, compteur5, nameC1, nameC2, nameC3, nameC4, nameC5, nil]; REVIEW: When I disallow ARC for the target, an warning persist. How I can resolve that please ? Thank you very much.

    Read the article

  • Retrieving a unique result set with Core Data

    - by randombits
    I have a core data based app that manages a bunch of entities. I'm looking to be able to do the following. I have an entity "SomeEntity" with the attributes: name, type, rank, foo1, foo2. Now, SomeEntity has several rows if when we're speaking strictly in SQL terms. What I'm trying to accomplish is to retrieve only available types, even though each instance can have duplicate types. I also need them returned in order according to rank. So in SQL, what I'm looking for is the following: SELECT DISTINCT(type) ORDER BY rank ASC Here is the code I have so far that's breaking: NSError *error = NULL; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setReturnsDistinctResults:YES]; [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"type", @"rank", nil]]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"SomeEntity" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // sort by rank NSSortDescriptor *rankDescriptor = [[NSSortDescriptor alloc] initWithKey:@"rank" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:rankDescriptor,nil]; [fetchRequest setSortDescriptors:sortDescriptors]; [sortDescriptors release]; [rankDescriptor release]; NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; [fetchRequest release]; return fetchResults; Right now that is crashing with the following: Invalid keypath section passed to setPropertiesToFetch:

    Read the article

  • Instance of method leaking, iPhone

    - by Wolfert
    The following method shows up as leaking while performing a memory-leaks test with Instruments: - (NSDictionary*) initSigTrkLstWithNiv:(int)pm_SigTrkNiv SigTrkSig:(int)pm_SigTrkSig SigResIdt:(int)pm_SigResIdt SigResVal:(int)pm_SigResVal { NSArray *objectArray; NSArray *keyArray; if (self = [super init]) { self.SigTrkNiv = [NSNumber numberWithInt:pm_SigTrkNiv]; self.SigTrkSig = [NSNumber numberWithInt:pm_SigTrkSig]; self.SigResIdt = [NSNumber numberWithInt:pm_SigResIdt]; self.SigResVal = [NSNumber numberWithInt:pm_SigResVal]; objectArray = [NSArray arrayWithObjects:SigTrkNiv,SigTrkSig,SigResIdt,SigResVal, nil]; keyArray = [NSArray arrayWithObjects:@"SigTrkNiv", @"SigTrkSig", @"SigResIdt", @"SigResVal", nil]; self = [NSDictionary dictionaryWithObjects:objectArray forKeys:keyArray]; } return self; } code that invokes the instance: NSDictionary *lv_SigTrkLst = [[SigTrkLst alloc]initSigTrkLstWithNiv:[[tempDict objectForKey:@"SigTrkNiv"] intValue] SigTrkSig:[[tempDict objectForKey:@"SigTrkSig"] intValue] SigResIdt:[[tempDict objectForKey:@"SigResIdt"] intValue] SigResVal:[[tempDict objectForKey:@"SigResVal"] intValue]]; [[QBDataContainer sharedDataContainer].SigTrkLstArray addObject:lv_SigTrkLst]; [lv_SigTrkLst release]; Instruments informs that 'SigTrkLst' is leaking. Even though I have released the instance? (I know that adding it to the array increments the retainCount by 1 but releasing it twice removes it from the array?)

    Read the article

  • Why won't my UISearchDisplayController fire the didSelectRowAtIndexPath moethod?

    - by John Wells
    I am having an odd problem when searching a UITableView using a UISearchDisplayController. The UITableViewController is a subclass of another UITableViewController with a working didSelectRowAtIndexPath method. Without searching the controller handles selections fine, sending the superclass a didSelectRowAtIndexPath call, but if I select a cell when searching the superclass receives nothing but the cell is highlighted. Below is the code from my subclass. @implementation AdvancedViewController @synthesize searchDisplayController, dict, filteredList; - (void)viewDidLoad { [super viewDidLoad]; // Programmatically set up search bar UISearchBar *mySearchBar = [[UISearchBar alloc] init]; mySearchBar.delegate = self; [mySearchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone]; [mySearchBar sizeToFit]; self.tableView.tableHeaderView = mySearchBar; // Programmatically set up search display controller searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self]; [self setSearchDisplayController:searchDisplayController]; [searchDisplayController setDelegate:self]; [searchDisplayController setSearchResultsDataSource:self]; // Parse data from server NSData * jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]]; NSArray * items = [[NSArray alloc] initWithArray:[[CJSONDeserializer deserializer] deserializeAsArray:jsonData error:nil]]; // Init variables dict = [[NSMutableDictionary alloc] init]; listIndex = [[NSMutableArray alloc] init]; fullList = [[NSMutableArray alloc] init]; filteredList = [[NSMutableArray alloc] init]; // Get each item and format it for the UI for(NSMutableArray * item in items) { // Get the first letter NSString * firstKey = [[[item objectAtIndex:0] substringWithRange:NSMakeRange(0,1)] uppercaseString]; // Put symbols and numbers in the same section if ([[firstKey stringByTrimmingCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] isEqualToString:@""]) firstKey = @"#"; // If there isn't a section with this key if (![listIndex containsObject:firstKey]) { // Add the key to the index for faster access (because it's already sorted) [listIndex addObject:firstKey]; // Add the key to the unordered dictionary [dict setObject:[NSMutableArray array] forKey:firstKey]; } // Add the object to the dictionary [[dict objectForKey:firstKey] addObject:[[NSMutableDictionary alloc] initWithObjects:item forKeys:[NSArray arrayWithObjects:@"name", @"url", nil]]]; // Add the object to the list for simple searching [fullList addObject:[[NSMutableDictionary alloc] initWithObjects:item forKeys:[NSArray arrayWithObjects:@"name", @"url", nil]]]; } filteredList = [NSMutableArray arrayWithCapacity:[fullList count]]; } #pragma mark - #pragma mark Table view data source // Custom method for object oriented data access - (NSString *)tableView:(UITableView *)tableView dataForRowAtIndexPath:(NSIndexPath *)indexPath withKey:(NSString *)key { return (NSString *)((tableView == self.searchDisplayController.searchResultsTableView) ? [[filteredList objectAtIndex:indexPath.row] objectForKey:key] : [[[dict objectForKey:[listIndex objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] valueForKey:key]); } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return (tableView == self.searchDisplayController.searchResultsTableView) ? 1 : (([listIndex count] > 0) ? [[dict allKeys] count] : 1); } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return (tableView == self.searchDisplayController.searchResultsTableView) ? [filteredList count] : [[dict objectForKey:[listIndex objectAtIndex:section]] count]; } - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { return (tableView == self.searchDisplayController.searchResultsTableView) ? [[NSArray alloc] initWithObjects:nil] : listIndex; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return (tableView == self.searchDisplayController.searchResultsTableView) ? @"" : [listIndex objectAtIndex:section]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *kCellID = @"cellID"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; } NSString * name = nil; // TODO: Make dataForRowAtIndexPath work here if (tableView == self.searchDisplayController.searchResultsTableView) { // NOTE: dataForRowAtIndexPath causes this to crash for some unknown reason. Maybe it is called before viewDidLoad and has no data? name = [[filteredList objectAtIndex:indexPath.row] objectForKey:@"name"]; } else { // This always works name = [self tableView:[self tableView] dataForRowAtIndexPath:indexPath withKey:@"name"]; } cell.textLabel.text = name; return cell; } #pragma mark Search Methods - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { // Clear the filtered array [self.filteredList removeAllObjects]; // Filter the array for (NSDictionary *item in fullList) { // Compare the item's name to the search text NSComparisonResult result = [[item objectForKey:@"name"] compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])]; if (result == NSOrderedSame) { // Add to the filtered array if it matches [self.filteredList addObject:item]; } } } - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { [self filterContentForSearchText:searchString scope: [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; // Return YES to cause the search result table view to be reloaded. return YES; } - (void)viewDidUnload { filteredList = nil; } @end

    Read the article

  • Accessing 2D array and passing string to label.text

    - by Amir
    Hi. I'm trying to create 2D array and initialize it with NSStrings. When I try to copy content of a cell from the array to a label.text, the application crashes. NSMutableArray *array = [NSMutableArray arrayWithCapacity:0]; [array addObject:[NSMutableArray arrayWithObjects: [NSArray arrayWithObjects: @"0-0", @"0-1", @"0-2", nil], [NSArray arrayWithObjects: @"1-0", @"1-1", @"1-2", nil], [NSArray arrayWithObjects: @"2-0", @"2-1", @"2-2", nil], nil]]; label.text = [[array objectAtIndex:0] objectAtIndex:0]; Any idea why and what am I doing wrong?

    Read the article

  • Self-relation messes up contents in fetching

    - by holographix
    Hi folks, I'm dealing with an annoying problem in core data I've got a table named Character, which is made as follows I'm filling the table in various steps: 1) fill the attributes of the table 2) fill the Character Relation (charRel) FYI charRel is defined as follows I'm feeding the contents by pulling the data from an xml, the feeding code is this curStr = [[NSMutableString stringWithString:[curStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]] retain]; NSLog(@"Parsing relation within these keys %@, in order to get'em associated",curStr); NSArray *chunks = [curStr componentsSeparatedByString: @","]; for( NSString *relId in chunks ) { NSLog(@"Associating %@ with id %@",[currentCharacter valueForKey:@"character_id"], relId); NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"character_id == %@", relId]; [request setEntity:[NSEntityDescription entityForName:@"Character" inManagedObjectContext:[self managedObjectContext] ]]; [request setPredicate:predicate]; NSerror *error = nil; NSArray *results = [[self managedObjectContext] executeFetchRequest:request error:&error]; // error handling code if(error != nil) { NSLog(@"[SYMBOL CORRELATION]: retrieving correlated symbol error: %@", [error localizedDescription]); } else if([results count] > 0) { Character *relatedChar = [results objectAtIndex:0]; // grab the first result in the stack, could be done better! [currentCharacter addCharRelObject:relatedChar]; //VICE VERSA RELATIONS NSArray *charRels = [relatedChar valueForKey:@"charRel"]; BOOL alreadyRelated = NO; for(Character *charRel in charRels) { if([[charRel valueForKey:@"character_id"] isEqual:[currentCharacter valueForKey:@"character_id"]]) { alreadyRelated = YES; break; } } if(!alreadyRelated) { NSLog(@"\n\t\trelating %@ with %@", [relatedChar valueForKey:@"character_id"], [currentCharacter valueForKey:@"character_id"]); [relatedChar addCharRelObject:currentCharacter]; } } else { NSLog(@"[SYMBOL CORRELATION]: related symbol was not found! ##SKIPPING-->"); } [request release]; } NSLog(@"\t\t### TOTAL OF REALTIONS FOR ID %@: %d\n%@", [currentCharacter valueForKey:@"character_id"], [[currentCharacter valueForKey:@"charRel"] count], currentCharacter); error = nil; /* SAVE THE CONTEXT */ if (![managedObjectContext save:&error]) { NSLog(@"Whoops, couldn't save the symbol record: %@", [error localizedDescription]); NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey]; if(detailedErrors != nil && [detailedErrors count] > 0) { for(NSError* detailedError in detailedErrors) { NSLog(@"\n################\t\tDetailedError: %@\n################", [detailedError userInfo]); } } else { NSLog(@" %@", [error userInfo]); } } at this point when I print out the values of the currentCharacter, everything looks perfect. every relation is in its place. in example in this log we can clearly see that this element has got 3 items in charRel: <Character: 0x5593af0> (entity: Character; id: 0x55938c0 <x-coredata://67288D50-D349-4B19-B7CB-F7AC4671AD61/Character/p86> ; data: { catRel = "<relationship fault: 0x9a29db0 'catRel'>"; charRel = ( "0x9a1f870 <x-coredata://67288D50-D349-4B19-B7CB-F7AC4671AD61/Character/p74>", "0x9a14bd0 <x-coredata://67288D50-D349-4B19-B7CB-F7AC4671AD61/Character/p109>", "0x558ba00 <x-coredata://67288D50-D349-4B19-B7CB-F7AC4671AD61/Character/p5>" ); "character_id" = 254; examplesRel = "<relationship fault: 0x9a29df0 'examplesRel'>"; meaning = "\n Left"; pinyin = "\n zu\U01d2"; "pronunciation_it" = "\n zu\U01d2"; strokenumber = 5; text = "\n \n <p>The most ancient form of this symbol"; unicodevalue = "\n \U5de6"; }) then when I'm in need of retrieving this item I perform an extraction, like this: // at first I get the single Character record NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSError *error; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"character_id == %@", self.char_id ]; [request setEntity:[NSEntityDescription entityForName:@"Character" inManagedObjectContext:_context ]]; [request setPredicate:predicate]; NSArray *fetchedObjs = [_context executeFetchRequest:request error:&error]; when, for instance, I print out in NSLog the contents of charRel NSArray *correlations = [singleCharacter valueForKey:@"charRel"]; NSLog(@"CHARACTER OBJECT \n%@", correlations); I get this Relationship fault for (<NSRelationshipDescription: 0x5568520>), name charRel, isOptional 1, isTransient 0, entity Character, renamingIdentifier charRel, validation predicates (), warnings (), versionHashModifier (null), destination entity Character, inverseRelationship (null), minCount 1, maxCount 99 on 0x6937f00 hope that I made myself clear. this thing is driving me insane, I've googled all over world, but I couldn't find a solution (and this make me think to as issue related to bad coding somehow :P). thank you in advance guys. k

    Read the article

  • Unexpected key-value behavior in a Core Data Context

    - by ????
    If I create an array of strings (via key-value coding) containing the names of a Managed Object entity's attributes which are stored in the App Delegate the first time, I get an array of NSStrings without any problems. If I subsequently make the same call later from the same entry point in code, that same collection becomes an array of NULL objects- even though nothing in the Core Data Context has changed. One unappealing work-around involves re-creating the string array every time, but I'm wondering if anyone has a guess as to what's happening behind the scenes. // Return an array of strings with the names of attributes the Activity entity - (NSArray *)activityAttributeNames { #pragma mark ALWAYS REFRESH THE ENTITY NAMES? //if (activityAttributeNames == nil) { // Create an entity pointer for Activity NSEntityDescription *entity = [NSEntityDescription entityForName:@"Activity" inManagedObjectContext:managedObjectContext]; NSArray *entityAttributeArray = [[NSArray alloc] initWithArray:[[entity attributesByName] allValues]]; // Extract the names of the attributes with Key-Value Coding activityAttributeNames = [entityAttributeArray valueForKeyPath:@"name"]; [entityAttributeArray release]; //} return activityAttributeNames; }

    Read the article

  • Store an array of UIViews in NSUserDefaults

    - by Mona
    I'm trying to add an array of uiviews to NSDefault but it doesn't seem to be keep the array. Does any one know why? I also tried to store each view in nsvalue before storing it in nsdefault which still didn't work. NSArray *arr = [[NSArray alloc] initWithObjects:[NSValue valueWithNonretainedObject:myView], nil]]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:arr forKey:@"myKey"]; NSArray *resultArray = [defaults objectForKey:@"myKey"]; and resultArray is nil! Thanks the reason why I'm trying to do this is because these are the header views of my uitableview. Since it takes time to create them I wanted to create them only once and store them for future access.

    Read the article

  • How to sort numbers in array from low to high

    - by Louie
    Hello all, I am trying to sort an array of prices from low to high. I have it working but not the way I want it to. Long story short, the sorter is putting numbers in order like this: 100 10900 200 290 instead of sorting like this 100 200 290 10900 here is my code I am doing this with. -(void)filterPriceLowHigh { NSSortDescriptor *sortDescriptor; sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"ListPrice" ascending:YES] autorelease]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; NSArray *sortedArray; sortedArray = [app.vehiclesArrayToDisplay sortedArrayUsingDescriptors:sortDescriptors]; [app.vehiclesArrayToDisplay removeAllObjects]; [app.vehiclesArrayToDisplay addObjectsFromArray:sortedArray]; } Could someone tell me what I need to do here? thanks in advance.

    Read the article

  • Save and Load Data on Today Extensions (iOS 8)

    - by Massimo Piazza
    Is it possible to save and load data on Today Extension using NSUserDefaults? After closing the Notification Center, the widget behaves like an app which is terminated, so any data results lost. How could I solve this issue? This is my code: NSUserDefaults *defaults; - (void)viewDidLoad { [super viewDidLoad]; defaults = [NSUserDefaults standardUserDefaults]; NSArray *loadStrings = [defaults stringArrayForKey:@"savedStrings"]; if ([loadStrings objectAtIndex:0] != nil) { [display setText:[NSString stringWithFormat:@"%@", [loadStrings objectAtIndex:0]]]; } if ([loadStrings objectAtIndex:1] != nil) { calculatorMemory = [NSString stringWithFormat:@"%@", [loadStrings objectAtIndex:1]].doubleValue; } } - (IBAction)saveData:(id)sender { NSString *displayString; NSString *memoryString; NSArray *saveStrings = [[NSArray alloc] initWithObjects: displayString, memoryString, nil]; defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:saveStrings forKey:@"savedStrings"]; [defaults synchronize]; }

    Read the article

  • recursive enumeration of integer subsets?

    - by KDaker
    I have an NSArray of NSNumbers with integer values such as [1,10,3]. I want to get the sum of all the possible subsets of these numbers. For example for 1,10 and 3 i would get: 1, 10, 3, 1+10=11, 1+3=4, 10+3=13, 1+10+3=14 there are 2^n possible combinations. I understand the math of it but im having difficulties putting this into code. so how can i put this into a method that would take the initial array of numbers and return an array with all the sums of the subsets? e.g -(NSArray *) getSums:(NSArray *)numbers; I understand that the results grow exponentially but im going to be using it for small sets of numbers.

    Read the article

  • UITableViewCell selected subview ghosts

    - by Jonathan Cohen
    Hi all, I'm learning about the iPhone SDK and have an interesting exception with UITableViewCell subview management when a finger is pressed on some rows. The table is used to assign sounds to hand gestures -- swiping the phone in one of 3 directions triggers the sound to play. Selecting a row displays an action sheet with 4 options for sound assignment: left, down, right, and cancel. Sounds can be mapped to one, two, or three directions so any cell can have one of seven states: left, down, right, left and down, left and right, down and right, or left down and right. If a row is mapped to any of these seven states, a corresponding arrow or arrows are displayed within the bounds of the row as a subview. Arrows come and go as they should in a given screen and when scrolling around. However, after scrolling to a new batch of rows, only when I press my finger down on some (but not all) rows, does an arrow magically appear in the selected state background. When I lift my finger off the row, and the action sheet appears, the arrow disappears. After pressing any of the four buttons, I can't replicate this anymore. But it's really disorienting and confusing to see this arrow flash on screen because the selected row isn't assigned to anything. What haven't I thought to look into here? All my table code is pasted below and this is a screencast of the problem: http://www.screencast.com/users/JonathanGCohen/folders/Jing/media/d483fe31-05b5-4c24-ab4d-70de4ff3a0bf Am I managing my subviews wrong or is there a selected state property I'm missing? Something else? Should I have included any more information in this post to make things clearer? Thank you!! #pragma mark - #pragma mark Table - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return ([categories count] > 0) ? [categories count] : 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if ([categories count] == 0) return 0; NSMutableString *key = [categories objectAtIndex:section]; NSMutableArray *nameSection = [categoriesSounds objectForKey:key]; return [nameSection count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger section = [indexPath section]; NSUInteger row = [indexPath row]; NSString *key = [categories objectAtIndex:section]; NSArray *nameSection = [categoriesSounds objectForKey:key]; static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SectionsTableIdentifier]; NSArray *sound = [categoriesSounds objectForKey:key]; NSString *soundName = [[sound objectAtIndex: row] objectAtIndex: 0]; NSString *soundOfType = [[sound objectAtIndex: row] objectAtIndex: 1]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SectionsTableIdentifier] autorelease]; } cell.textLabel.text = [[nameSection objectAtIndex:row] objectAtIndex: 0]; NSUInteger soundSection = [[[sound objectAtIndex: row] objectAtIndex: 2] integerValue]; NSUInteger soundRow = [[[sound objectAtIndex: row] objectAtIndex: 3] integerValue]; NSUInteger leftRow = [leftOldIndexPath row]; NSUInteger leftSection = [leftOldIndexPath section]; if (soundRow == leftRow && soundSection == leftSection && leftOldIndexPath !=nil){ [selectedSoundLeftAndDown removeFromSuperview]; [selectedSoundLeftAndRight removeFromSuperview]; [cell.contentView addSubview: selectedSoundLeft]; selectedSoundLeft.frame = CGRectMake(200,8,30,30); } else { [cell.contentView sendSubviewToBack: selectedSoundLeft]; } NSUInteger downRow = [downOldIndexPath row]; NSUInteger downSection = [downOldIndexPath section]; if (soundRow == downRow && soundSection == downSection && downOldIndexPath !=nil){ [selectedSoundLeftAndDown removeFromSuperview]; [selectedSoundDownAndRight removeFromSuperview]; [cell.contentView addSubview: selectedSoundDown]; selectedSoundDown.frame = CGRectMake(200,8,30,30); } else { [cell.contentView sendSubviewToBack: selectedSoundDown]; } NSUInteger rightRow = [rightOldIndexPath row]; NSUInteger rightSection = [rightOldIndexPath section]; if (soundRow == rightRow && soundSection == rightSection && rightOldIndexPath !=nil){ [selectedSoundDownAndRight removeFromSuperview]; [selectedSoundLeftAndRight removeFromSuperview]; [cell.contentView addSubview: selectedSoundRight]; selectedSoundRight.frame = CGRectMake(200,8,30,30); } else { [cell.contentView sendSubviewToBack: selectedSoundRight]; } // combos if (soundRow == leftRow && soundRow == downRow && soundSection == leftSection && soundSection == downSection){ [selectedSoundLeft removeFromSuperview]; [selectedSoundDown removeFromSuperview]; [selectedSoundLeftAndDownAndRight removeFromSuperview]; [cell.contentView addSubview: selectedSoundLeftAndDown]; selectedSoundLeftAndDown.frame = CGRectMake(200,8,30,30); } else { [cell.contentView sendSubviewToBack: selectedSoundLeftAndDown]; } if (soundRow == leftRow && soundRow == rightRow && soundSection == leftSection && soundSection == rightSection){ [selectedSoundLeft removeFromSuperview]; [selectedSoundRight removeFromSuperview]; [selectedSoundLeftAndDownAndRight removeFromSuperview]; [cell.contentView addSubview: selectedSoundLeftAndRight]; selectedSoundLeftAndRight.frame = CGRectMake(200,8,30,30); } else { [cell.contentView sendSubviewToBack: selectedSoundLeftAndRight]; } if (soundRow == downRow && soundRow == rightRow && soundSection == downSection && soundSection == rightSection){ [selectedSoundDown removeFromSuperview]; [selectedSoundRight removeFromSuperview]; [selectedSoundLeftAndDownAndRight removeFromSuperview]; [cell.contentView addSubview: selectedSoundDownAndRight]; selectedSoundDownAndRight.frame = CGRectMake(200,8,30,30); } else { [cell.contentView sendSubviewToBack: selectedSoundDownAndRight]; } if (soundRow == leftRow && soundRow == downRow && soundRow == rightRow && soundSection == leftSection && soundSection == downSection && soundSection == rightSection){ [selectedSoundLeftAndDown removeFromSuperview]; [selectedSoundLeftAndRight removeFromSuperview]; [selectedSoundDownAndRight removeFromSuperview]; [selectedSoundLeft removeFromSuperview]; [selectedSoundDown removeFromSuperview]; [selectedSoundRight removeFromSuperview]; [cell.contentView addSubview: selectedSoundLeftAndDownAndRight]; selectedSoundLeftAndDownAndRight.frame = CGRectMake(200,8,30,30); } else { [cell.contentView sendSubviewToBack: selectedSoundLeftAndDownAndRight]; } [indexPath retain]; return cell; } - (NSMutableString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { if ([categories count] == 0) return nil; NSMutableString *key = [categories objectAtIndex:section]; if (key == UITableViewIndexSearch) return nil; return key; } - (NSMutableArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { if (isSearching) return nil; return categories; } - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { [table reloadData]; [selectedSoundLeft removeFromSuperview]; [selectedSoundDown removeFromSuperview]; [selectedSoundRight removeFromSuperview]; [selectedSoundLeftAndDown removeFromSuperview]; [selectedSoundLeftAndRight removeFromSuperview]; [selectedSoundDownAndRight removeFromSuperview]; [selectedSoundLeftAndDownAndRight removeFromSuperview]; [search resignFirstResponder]; if (isSearching == YES && [search.text length] != 0 ){ searched = YES; } search.text = @""; isSearching = NO; [tableView reloadData]; [indexPath retain]; [indexPath retain]; return indexPath; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [table reloadData]; selectedIndexPath = indexPath; [table reloadData]; NSInteger section = [indexPath section]; NSInteger row = [indexPath row]; NSString *key = [categories objectAtIndex:section]; NSArray *sound = [categoriesSounds objectForKey:key]; NSString *soundName = [[sound objectAtIndex: row] objectAtIndex: 0]; [indexPath retain]; [indexPath retain]; NSMutableString *title = [NSMutableString stringWithString: @"Assign Gesture for "]; NSMutableString *soundFeedback = [NSMutableString stringWithString: (@"%@", soundName)]; [title appendString: soundFeedback]; UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:(@"%@", title) delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle: nil otherButtonTitles:@"Left",@"Down",@"Right",nil]; action.actionSheetStyle = UIActionSheetStyleDefault; [action showInView:self.view]; [action release]; } - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{ NSInteger section = [selectedIndexPath section]; NSInteger row = [selectedIndexPath row]; NSString *key = [categories objectAtIndex:section]; NSArray *sound = [categoriesSounds objectForKey:key]; NSString *soundName = [[sound objectAtIndex: row] objectAtIndex: 0]; NSString *soundOfType = [[sound objectAtIndex: row] objectAtIndex: 1]; NSUInteger soundSection = [[[sound objectAtIndex: row] objectAtIndex: 2] integerValue]; NSUInteger soundRow = [[[sound objectAtIndex: row] objectAtIndex: 3] integerValue]; NSLog(@"sound row is %i", soundRow); NSLog(@"sound section is row is %i", soundSection); typedef enum { kLeftButton = 0, kDownButton, kRightButton, kCancelButton } gesture; switch (buttonIndex) { //Left case kLeftButton: showLeft.text = soundName; left = [[NSBundle mainBundle] pathForResource:(@"%@", soundName) ofType:(@"%@", soundOfType)]; AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:left], &soundNegZ); AudioServicesPlaySystemSound (soundNegZ); [table deselectRowAtIndexPath:selectedIndexPath animated:YES]; leftIndexSection = [NSNumber numberWithInteger:section]; leftIndexRow = [NSNumber numberWithInteger:row]; NSInteger leftSection = [leftIndexSection integerValue]; NSInteger leftRow = [leftIndexRow integerValue]; NSString *leftKey = [categories objectAtIndex: leftSection]; NSArray *leftSound = [categoriesSounds objectForKey:leftKey]; NSInteger leftSoundSection = [[[leftSound objectAtIndex: leftRow] objectAtIndex: 2] integerValue]; NSInteger leftSoundRow = [[[leftSound objectAtIndex: leftRow] objectAtIndex: 3] integerValue]; leftOldIndexPath = [NSIndexPath indexPathForRow:leftSoundRow inSection:leftSoundSection]; break; //Down case kDownButton: showDown.text = soundName; down = [[NSBundle mainBundle] pathForResource:(@"%@", soundName) ofType:(@"%@", soundOfType)]; AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:down], &soundNegX); AudioServicesPlaySystemSound (soundNegX); [table deselectRowAtIndexPath:selectedIndexPath animated:YES]; downIndexSection = [NSNumber numberWithInteger:section]; downIndexRow = [NSNumber numberWithInteger:row]; NSInteger downSection = [downIndexSection integerValue]; NSInteger downRow = [downIndexRow integerValue]; NSString *downKey = [categories objectAtIndex: downSection]; NSArray *downSound = [categoriesSounds objectForKey:downKey]; NSInteger downSoundSection = [[[downSound objectAtIndex: downRow] objectAtIndex: 2] integerValue]; NSInteger downSoundRow = [[[downSound objectAtIndex: downRow] objectAtIndex: 3] integerValue]; downOldIndexPath = [NSIndexPath indexPathForRow:downSoundRow inSection:downSoundSection]; break; //Right case kRightButton: showRight.text = soundName; right = [[NSBundle mainBundle] pathForResource:(@"%@", soundName) ofType:(@"%@", soundOfType)]; AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:right], &soundPosX); AudioServicesPlaySystemSound (soundPosX); [table deselectRowAtIndexPath:selectedIndexPath animated:YES]; rightIndexSection = [NSNumber numberWithInteger:section]; rightIndexRow = [NSNumber numberWithInteger:row]; NSInteger rightSection = [rightIndexSection integerValue]; NSInteger rightRow = [rightIndexRow integerValue]; NSString *rightKey = [categories objectAtIndex: rightSection]; NSArray *rightSound = [categoriesSounds objectForKey:rightKey]; NSInteger rightSoundSection = [[[rightSound objectAtIndex: rightRow] objectAtIndex: 2] integerValue]; NSInteger rightSoundRow = [[[rightSound objectAtIndex: rightRow] objectAtIndex: 3] integerValue]; rightOldIndexPath = [NSIndexPath indexPathForRow:rightSoundRow inSection:rightSoundSection]; break; case kCancelButton: [table deselectRowAtIndexPath:selectedIndexPath animated:YES]; break; default: break; } UITableViewCell *viewCell = [table cellForRowAtIndexPath: selectedIndexPath]; NSArray *subviews = viewCell.subviews; for (UIView *cellView in subviews){ cellView.alpha = 1; } [table reloadData]; } - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSMutableString *)title atIndex:(NSInteger)index { NSMutableString *category = [categories objectAtIndex:index]; if (category == UITableViewIndexSearch) { [tableView setContentOffset:CGPointZero animated:NO]; return NSNotFound; } else return index; }

    Read the article

  • IOS Variable vs Property

    - by William Smith
    Just started diving into Objective-C and IOS development and was wondering when and the correct location I should be declaring variables/properties. The main piece of code i need explaining is below: Why and when should i be declaring variables inside the interface statement and why do they have the same variable with _ and then the same one as a property. And then in the implementation they do @synthesize tableView = _tableView (I understand what synthesize does) Thanks :-) @interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> { UITableView *_tableView; UIActivityIndicatorView *_activityIndicatorView; NSArray *_movies; } @property (nonatomic, retain) UITableView *tableView; @property (nonatomic, retain) UIActivityIndicatorView *activityIndicatorView; @property (nonatomic, retain) NSArray *movies;

    Read the article

  • App crashes after a few seconds

    - by Declan Scott
    when i launch my app, on trying to do something, it will crash after a couple of seconds. I have warnings of warning: incorrect implementation of "downloadTextViewCOntroller. I also have "method definiton for -timerFinished not found and"method definiton for -timerFinished not found" this is my .m plese help me. the .h is also t the bottom // // downloadTextViewController.m // downloadText // // Created by Declan Scott on 18/03/10. // Copyright MyCompanyName 2010. All rights reserved. // #import "downloadTextViewController.h" @implementation downloadTextViewController @synthesize start; -(IBAction)tapit { start.hidden = YES; } -(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { if (fabsf(acceleration.x) 2.0 || fabsf(acceleration.y) 2.0 || fabsf(acceleration.z) 2.0) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"This app was developed by Declan Scott and demonstrates NSURLConnection and NSMutableData" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } } (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)viewDidLoad { UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer]; accelerometer.delegate = self; accelerometer.updateInterval = 1.0f/60.0f; 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]; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (IBAction)fetchData { loadingAlert = [[UIAlertView alloc] initWithTitle:@"Loading…\n\n\n\n" message:nil delegate:self cancelButtonTitle:@"Cancel Timer" otherButtonTitles:nil]; [loadingAlert show]; UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; activityView.frame = CGRectMake(139.0f-18.0f, 60.0f, 37.0f, 37.0f); [loadingAlert addSubview:activityView]; [activityView startAnimating]; timer = [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(timerFinished) userInfo:nil repeats:NO]; 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 } } (void)connection:(NSURLConnection *)downloadConnection didReceiveData:(NSData *)data { [downloadedData appendData:data]; NSString *file = [[NSString alloc] initWithData:downloadedData encoding:NSUTF8StringEncoding]; textView.text = file; // get rid of alert [loadingAlert dismissWithClickedButtonIndex:-1 animated:YES]; [loadingAlert release]; /// add badge [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1]; } (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 // // downloadTextViewController.h // downloadText // // Created by Declan Scott on 18/03/10. // Copyright MyCompanyName 2010. All rights reserved. // import @interface downloadTextViewController : UIViewController { IBOutlet UITextView *textView; NSMutableData *downloadedData; UIAlertView *loadingAlert; NSTimer *timer; IBOutlet UIButton *start; } - (IBAction)fetchData; - (IBAction)tapIt; - (void)timerFinished; @property (nonatomic, retain) UIButton *start; @end

    Read the article

  • Can't get Jacobi algorithm to work in Objective-C

    - by Chris Long
    Hi, For some reason, I can't get this program to work. I've had other CS majors look at it and they can't figure it out either. This program performs the Jacobi algorithm (you can see step-by-step instructions and a MATLAB implementation here). BTW, it's different from the Wikipedia article of the same name. Since NSArray is one-dimensional, I added a method that makes it act like a two-dimensional C array. After running the Jacobi algorithm many times, the diagonal entries in the NSArray (i[0][0], i[1][1], etc.) are supposed to get bigger and the others approach 0. For some reason though, they all increase exponentially. For instance, i[2][4] should equal 0.0000009, not 9999999, while i[2][2] should be big. Thanks in advance, Chris NSArray+Matrix.m @implementation NSArray (Matrix) @dynamic offValue, transposed; - (double)offValue { double sum = 0.0; for ( MatrixItem *item in self ) if ( item.nonDiagonal ) sum += pow( item.value, 2.0 ); return sum; } - (NSMutableArray *)transposed { NSMutableArray *transpose = [[[NSMutableArray alloc] init] autorelease]; int i, j; for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 5; j++ ) { [transpose addObject:[self objectAtRow:j andColumn:i]]; } } return transpose; } - (id)objectAtRow:(NSUInteger)row andColumn:(NSUInteger)column { NSUInteger index = 5 * row + column; return [self objectAtIndex:index]; } - (NSMutableArray *)multiplyWithMatrix:(NSArray *)array { NSMutableArray *result = [[NSMutableArray alloc] init]; int i = 0, j = 0, k = 0; double value; for ( i = 0; i < 5; i++ ) { value = 0.0; for ( j = 0; j < 5; j++ ) { for ( k = 0; k < 5; k++ ) { MatrixItem *firstItem = [self objectAtRow:i andColumn:k]; MatrixItem *secondItem = [array objectAtRow:k andColumn:j]; value += firstItem.value * secondItem.value; } MatrixItem *item = [[MatrixItem alloc] initWithValue:value]; item.row = i; item.column = j; [result addObject:item]; } } return result; } @end Jacobi_AlgorithmAppDelegate.m // ... - (void)jacobiAlgorithmWithEntry:(MatrixItem *)entry { MatrixItem *b11 = [matrix objectAtRow:entry.row andColumn:entry.row]; MatrixItem *b22 = [matrix objectAtRow:entry.column andColumn:entry.column]; double muPlus = ( b22.value + b11.value ) / 2.0; muPlus += sqrt( pow((b22.value - b11.value), 2.0) + 4.0 * pow(entry.value, 2.0) ); Vector *u1 = [[[Vector alloc] initWithX:(-1.0 * entry.value) andY:(b11.value - muPlus)] autorelease]; [u1 normalize]; Vector *u2 = [[[Vector alloc] initWithX:-u1.y andY:u1.x] autorelease]; NSMutableArray *g = [[[NSMutableArray alloc] init] autorelease]; for ( int i = 0; i <= 24; i++ ) { MatrixItem *item = [[[MatrixItem alloc] init] autorelease]; if ( i == 6*entry.row ) item.value = u1.x; else if ( i == 6*entry.column ) item.value = u2.y; else if ( i == ( 5*entry.row + entry.column ) || i == ( 5*entry.column + entry.row ) ) item.value = u1.y; else if ( i % 6 == 0 ) item.value = 1.0; else item.value = 0.0; [g addObject:item]; } NSMutableArray *firstResult = [[g.transposed multiplyWithMatrix:matrix] autorelease]; matrix = [firstResult multiplyWithMatrix:g]; } // ...

    Read the article

  • How to display data stored in core data in a table view?

    - by Dipanjan Dutta
    Hello All, I have developed a core data model for my application. I need to display the saved data into a table view. For my app I have selected split view controller. I am writing down my codes below. Please help me in this regard and write me the code that needs to be added. This is very important as my continuation in my company depends on this. #import "RootViewController.h" #import "DetailViewController.h" #import "AddViewController.h" #import "EmployeeDetailsAppDelegate.h" /* This template does not ensure user interface consistency during editing operations in the table view. You must implement appropriate methods to provide the user experience you require. */ @interface RootViewController () - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath; @end @implementation RootViewController @synthesize detailViewController, fetchedResultsController, managedObjectContext, results, empName; #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { results = [[NSMutableDictionary alloc]init]; [results setObject:empName.text forKey:@"EmployeeName"]; [self.tableView reloadData]; [super viewDidLoad]; } /* - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } */ /* - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } */ /* - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } */ /* - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } */ - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape. return YES; } - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; cell.textLabel.text = [[managedObject valueForKey:@"EmployeeName"] description]; } #pragma mark - #pragma mark Add a new object - (void)insertNewObject:(id)sender { AddViewController *add = [[AddViewController alloc]initWithNibName:@"AddViewController" bundle:nil]; self.modalPresentationStyle = UIModalPresentationFormSheet; add.wantsFullScreenLayout = NO; [self presentModalViewController:add animated:YES]; [add release]; } #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell. NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; cell.textLabel.text = [[managedObject valueForKey:@"EmployeeName"] description]; return cell; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the managed object. NSManagedObject *objectToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath]; if (self.detailViewController.detailItem == objectToDelete) { self.detailViewController.detailItem = nil; } NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; [context deleteObject:objectToDelete]; NSError *error; if (![context save:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } } } - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // The table view should not be re-orderable. return NO; } #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Set the detail item in the detail view controller. NSManagedObject *selectedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; self.detailViewController.detailItem = selectedObject; } #pragma mark - #pragma mark Fetched results controller - (NSFetchedResultsController *)fetchedResultsController { if (fetchedResultsController != nil) { return fetchedResultsController; } /* Set up the fetched results controller. */ // Create the fetch request for the entity. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; // Edit the entity name as appropriate. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Details" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; // Set the batch size to a suitable number. [fetchRequest setFetchBatchSize:20]; // Edit the sort key as appropriate. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"EmployeeName" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". 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; } #pragma mark - #pragma mark Fetched results controller delegate - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { [self.tableView beginUpdates]; } - (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)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:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; break; case NSFetchedResultsChangeMove: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade]; break; } } - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.tableView endUpdates]; } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Relinquish ownership any cached data, images, etc. that aren't in use. } - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; } - (void)dealloc { [detailViewController release]; [fetchedResultsController release]; [managedObjectContext release]; [super dealloc]; } @end // // AddViewController.m // EmployeeDetails // // Created by Dipanjan on 15/02/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import "AddViewController.h" #import "EmployeeDetailsAppDelegate.h" #import "RootViewController.h" @implementation AddViewController @synthesize empName; @synthesize empID; @synthesize empDepartment; @synthesize backButton; // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. /* - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization. } return self; } */ /* // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; } */ -(void)saveDetails{ EmployeeDetailsAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate]; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSManagedObject *newDetails; newDetails = [NSEntityDescription insertNewObjectForEntityForName:@"Details" inManagedObjectContext:context]; [newDetails setValue:empID.text forKey:@"EmployeeID"]; [newDetails setValue:empName.text forKey:@"EmployeeName"]; [newDetails setValue:empDepartment.text forKey:@"EmployeeDepartment"]; empID.text = @""; empName.text = @""; empDepartment.text = @""; NSLog(@"%@........----->>>...", newDetails); NSError *error; [context save:&error]; [self dismissModalViewControllerAnimated:YES]; } -(void)findDetails { EmployeeDetailsAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate]; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Details" inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc]init]; [request setEntity:entityDesc]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"(EmployeeName = %@)", empName.text]; [request setPredicate:pred]; NSManagedObject *matches = nil; NSError *error; NSArray *objects = [context executeFetchRequest:request error:&error]; if ([objects count] == 0) { } else { matches = [objects objectAtIndex:0]; empID.text = [matches valueForKey:@"EmployeeID"]; empDepartment.text = [matches valueForKey:@"EmployeeDepartment"]; } [request release]; [self dismissModalViewControllerAnimated:YES]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Overriden to allow any orientation. return YES; } - (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 { self.empName = nil; self.empID = nil; self.empDepartment = nil; [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [empID release]; [empName release]; [empDepartment release]; [super dealloc]; } @end Please let me know the answer as soon as possible. Thank you. Regards, Dipanjan

    Read the article

  • Get 1 array from 2 arrays (using RestKit 0.20)

    - by Reez
    I'm using RestKit and was wondering how to combine two array's into one array. I already have the data being pulled in separately from API1 and API2, but I don't know how to combine them into 1 tableView. Each API is pulling in media, and I want the combined tableView to show the most recent media (like any standard timeline does these days). I will post any extra code or help as necessary, thanks so much! Below shows API1 + API2 being pulled in correctly, but not combined into the tableView. Only data from API1 shows in the tableView. ViewController.m @interface StackOverflowViewController () @property (strong, nonatomic) NSArray *hArray; @property (strong, nonatomic) NSArray *springs; @property (strong, nonatomic) RKObjectManager *eObjectManager; @property (strong, nonatomic) NSArray *iArray; @property (strong, nonatomic) NSArray *imagesArray; @property (strong, nonatomic) RKObjectManager *iObjectManager; // Wain @property (strong, nonatomic) NSMutableArray *tableDataList; // Laarme @property (nonatomic, strong) NSMutableArray *contentArray; @property (nonatomic, strong) NSDateFormatter *dateFormatter1; // Dan @property (nonatomic, strong) NSMutableArray *combinedModel; @end @implementation StackOverflowViewController @synthesize tableView = _tableView; @synthesize spring; @synthesize leaf; @synthesize theme; @synthesize hArray; @synthesize springs; @synthesize eObjectManager; @synthesize iArray; @synthesize imagesArray; @synthesize iObjectManager; // Wain @synthesize tableDataList; // Laarme @synthesize contentArray; @synthesize dateFormatter1; // Dan @synthesize combinedModel; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self configureRestKit]; [self loadMediaDan]; [self sortCombinedModel]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)configureRestKit { // API1 // initialize AFNetworking HTTPClient NSURL *baseURLE = [NSURL URLWithString:@"https://api.e.com"]; AFHTTPClient *clientE = [[AFHTTPClient alloc] initWithBaseURL:baseURLE]; // initialize RestKit RKObjectManager *eManager = [[RKObjectManager alloc] initWithHTTPClient:clientE]; self.eObjectManager = eManager; // setup object mappings RKObjectMapping *feedMapping = [RKObjectMapping mappingForClass:[Feed class]]; [feedMapping addAttributeMappingsFromArray:@[@"headline", @"premium", @"published", @"description"]]; RKObjectMapping *linksMapping = [RKObjectMapping mappingForClass:[Links class]]; RKObjectMapping *webMapping = [RKObjectMapping mappingForClass:[Web class]]; [webMapping addAttributeMappingsFromArray:@[@"href"]]; RKObjectMapping *mobileMapping = [RKObjectMapping mappingForClass:[Mobile class]]; [mobileMapping addAttributeMappingsFromArray:@[@"href"]]; RKObjectMapping *imagesMapping = [RKObjectMapping mappingForClass:[Images class]]; [imagesMapping addAttributeMappingsFromArray:@[@"height", @"width", @"url"]]; [feedMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"links" toKeyPath:@"links" withMapping:linksMapping]]; [feedMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"images" toKeyPath:@"images" withMapping:imagesMapping]]; [linksMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"web" toKeyPath:@"web" withMapping:webMapping]]; [linksMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"mobile" toKeyPath:@"mobile" withMapping:mobileMapping]]; // register mappings with the provider using a response descriptor RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:feedMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"feed" statusCodes:[NSIndexSet indexSetWithIndex:200]]; [self.eObjectManager addResponseDescriptor:responseDescriptor]; // API2 // initialize AFNetworking HTTPClient NSURL *baseURLI = [NSURL URLWithString:@"https://api.i.com"]; AFHTTPClient *clientI = [[AFHTTPClient alloc] initWithBaseURL:baseURLI]; // initialize RestKit RKObjectManager *iManager = [[RKObjectManager alloc] initWithHTTPClient:clientI]; self.iObjectManager = iManager; // setup object mappings RKObjectMapping *dataMapping = [RKObjectMapping mappingForClass:[Data class]]; [dataMapping addAttributeMappingsFromArray:@[@"link", @"created_time"]]; RKObjectMapping *imagesMapping = [RKObjectMapping mappingForClass:[ImagesI class]]; [IMapping addAttributeMappingsFromArray:@[@""]]; RKObjectMapping *standardResolutionMapping = [RKObjectMapping mappingForClass:[StandardResolution class]]; [standardResolutionMapping addAttributeMappingsFromArray:@[@"url", @"width", @"height"]]; RKObjectMapping *captionMapping = [RKObjectMapping mappingForClass:[Caption class]]; [captionMapping addAttributeMappingsFromArray:@[@"text", @"created_time"]]; RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class]]; [userMapping addAttributeMappingsFromArray:@[@"username"]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"images" toKeyPath:@"images" withMapping:imagesMapping]]; [imagesMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"standard_resolution" toKeyPath:@"standard_resolution" withMapping:standardResolutionMapping]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"caption" toKeyPath:@"caption" withMapping:captionMapping]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"user" toKeyPath:@"user" withMapping:userMapping]]; // register mappings with the provider using a response descriptor RKResponseDescriptor *responseDescriptor2 = [RKResponseDescriptor responseDescriptorWithMapping:dataMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"data" statusCodes:[NSIndexSet indexSetWithIndex:200]]; [self.iObjectManager addResponseDescriptor:responseDescriptor2]; } - (void)loadMedia { // Laarme contentArray = [[NSMutableArray alloc] init]; [self sortByDates]; // API1 NSString *apikey = @kCLIENTKEY; NSDictionary *queryParams = @{@"apikey" : apikey,}; [self.eObjectManager getObjectsAtPath:[NSString stringWithFormat:@"v1/n/?limit=4&leafs=%@&themes=%@", leafAbbreviation, themeID] // Changed limit to 4 for the time being parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { hArray = mappingResult.array; [self.tableView reloadData]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"No?: %@", error); }]; // API2 [self.iObjectManager getObjectsAtPath:[NSString stringWithFormat:@"v1/u/2/m/recent/?client_id=e999"] parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { iArray = mappingResult.array; [self.tableView reloadData]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"No: %@", error); }]; } // Laarme - (void)sortByDates { NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init]; //Do the dateFormatter settings, you may have to use 2 NSDateFormatters if the format is different for Data & Feed //The initialization of the dateFormatter is done before the block, because its alloc/init take some time, and you may have to declare it with "__block" //Since in your edit you do that and it seems it's the same format, just do @property (nonatomic, strong) NSDateFormatter dateFormatter; NSArray *sortedArray = [contentArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { // Added Curly Braces around if else statements and used feedObject NSDate *aDate, *bDate; Feed *feedObject = (Feed *)a; Data *dataObject = (Data *)b; if ([a isKindOfClass:[Feed class]]) { //Feed *feedObject = (Feed *)a; aDate = [dateFormatter1 dateFromString:feedObject.published];} else { //if ([a isKindOfClass:[Data class]]) aDate = [dateFormatter2 dateFromString:dataObject.created_time];} if ([b isKindOfClass:[Feed class]]) { bDate = [dateFormatter1 dateFromString:feedObject.published];} else {//if ([b isKindOfClass:[Data class]]) bDate = [dateFormatter2 dateFromString:dataObject.created_time];} return [aDate compare:bDate]; }]; } #pragma mark - Table View - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // API1 //return hArray.count; // API2 //return iArray.count; // API1 + API2 return hArray.count + iArray.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell; if(indexPath.row < hArray.count) { // Date Change NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMMM d, yyyy h:mma"]; // API 1 TableViewCell *api1Cell = [tableView dequeueReusableCellWithIdentifier:@"YourAPI1Cell"]; // Do everything you need to do with the api1Cell // Use the index in 'indexPath.row' to get the object from you array // API1 Feed *feedLocal = [hArray objectAtIndex:indexPath.row]; // API1 NSString *dateString = [self timeSincePublished:feedLocal.published]; NSString *headlineText = [NSString stringWithFormat:@"%@", feedLocal.headline]; NSString *descriptionText = [NSString stringWithFormat:@"%@", feedLocal.description]; NSString *premiumText = [NSString stringWithFormat:@"%@", feedLocal.premium]; api1Cell.labelHeadline.text = [NSString stringWithFormat:@"%@", headlineText]; api1Cell.labelPublished.text = dateString; api1Cell.labelDescription.text = descriptionText; // SDWebImage API1 if ([feedLocal.images count] == 0) { // Not sure anything needed here } else { Images *imageLocal = [feedLocal.images objectAtIndex:0]; NSString *imageURL = [NSString stringWithFormat:@"%@", imageLocal.url]; NSString *imageWith = [NSString stringWithFormat:@"%@", imageLocal.width]; NSString *imageHeight = [NSString stringWithFormat:@"%@", imageLocal.height]; __weak UITableViewCell *wcell = cell; [cell.imageView setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"X"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // Something }]; } cell = api1Cell; } else { // Date Change NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMMM d, yyyy h:mma"]; // API 2 MRWebListTableViewCellTwo *api2Cell = [tableView dequeueReusableCellWithIdentifier:@"YourAPI2Cell"]; // Do everything you need to do with the api2Cell // Remember to use 'indexPath.row - hArray.count' as the index for getting an object for your second array // API 2 Data *dataLocal = [iArray objectAtIndex:indexPath.row - hArray.count]; // API 2 NSString *dateStringI = [self timeSincePublished:dataLocal.created_time]; NSString *captionTextI = [NSString stringWithFormat:@"%@", dataLocal.caption.text]; NSString *usernameI = [NSString stringWithFormat:@"%@", dataLocal.user.username]; api2Cell.labelHeadline.text = usernameI; api2Cell.labelDescription.text = captionTextI; api2Cell.labelPublished.text = dateStringI; // SDWebImage API 2 if ([dataLocal.images count] == 0) { NSLog(@"Images Count: %lu", (unsigned long)dataLocal.images.count); // Not sure anything needed here } else { ImagesI *imageLocalI = [dataLocal.images objectAtIndex:0]; StandardResolutionI *standardResolutionLocal = [imageLocalI.standard_resolution objectAtIndex:0]; NSString *imageURLI = [NSString stringWithFormat:@"%@", standardResolutionLocal.url]; NSString *imageWithI = [NSString stringWithFormat:@"%@", standardResolutionLocal.width]; NSString *imageHeightI = [NSString stringWithFormat:@"%@", standardResolutionLocal.height]; // 11.2 __weak UITableViewCell *wcell = cell; [cell.imageView setImageWithURL:[NSURL URLWithString:imageURLI] placeholderImage:[UIImage imageNamed:@"X"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // Something }]; } cell = api2Cell; } return cell; } Feed.h @property (nonatomic, strong) Links *links; @property (nonatomic, strong) NSString *headline; @property (nonatomic, strong) NSString *source; @property (nonatomic, strong) NSDate *published; @property (nonatomic, strong) NSString *description; @property (nonatomic, strong) NSString *premium; @property (nonatomic, strong) NSArray *images; Data.h @property (nonatomic, strong) NSString *link; @property (nonatomic, strong) NSDate *created_time; @property (nonatomic, strong) UserI *user; @property (nonatomic, strong) NSArray *images; @property (nonatomic, strong) CaptionI *caption;

    Read the article

  • Set the width and height for a TTLauncherItem

    - by Koning Baard
    I have this: _launcherView.pages = [NSArray arrayWithObjects: [NSArray arrayWithObjects: [[[TTLauncherItem alloc] initWithTitle:@"New Note" image:@"bundle://Icon.png" style:TTSTYL URL:@"http://www.google.com/" canDelete:NO] autorelease], [[[TTLauncherItem alloc] initWithTitle:@"To Do Items" image:@"bundle://Icon.png" URL:@"http://www.yahoo.com/" canDelete:NO] autorelease], nil], nil]; How can I set the width and height for the items? I want all items to be 64x64 pixels. Thanks

    Read the article

  • How to resolve warning about does not implement the 'UIActionSheetDelegate' protocol

    - by RAGOpoR
    here is my .h code @interface ROSettingViewController : UITableViewController { UISwitch *switchCtl; UISwitch *switchCtl1; NSArray *dataSourceArray; } @property (nonatomic, retain, readonly) UISwitch *switchCtl; @property (nonatomic, retain, readonly) UISwitch *switchCtl1; @property (nonatomic, retain) NSArray *dataSourceArray; - (void)dialogOKCancelAction; - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex; @end /Users/ragopor/Desktop/Power Spot beta 2/code/Classes/ROSettingViewController.m:321: warning: class 'ROSettingViewController' does not implement the 'UIActionSheetDelegate' protocol

    Read the article

  • Detect same image names {iPhone SDK}

    - by Momeks
    hi , i want create image animation , i have 50 images with png format now i want set images name ... something like this but doesnt work ! my images name are : iamge_0000 to image_0050 NSArray *myImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"image_%d.png"], //image named doesnt work ??!?!?!?

    Read the article

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