Search Results

Search found 3244 results on 130 pages for 'nil'.

Page 19/130 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • Permuting output of a tree of closures

    - by yan
    This a conceptual question on how one would implement the following in Lisp (assuming Common Lisp in my case, but any dialect would work). Assume you have a function that creates closures that sequentially iterate over an arbitrary collection (or otherwise return different values) of data and returns nil when exhausted, i.e. (defun make-counter (up-to) (let ((cnt 0)) (lambda () (if (< cnt up-to) (incf cnt) nil)))) CL-USER> (defvar gen (make-counter 3)) GEN CL-USER> (funcall gen) 1 CL-USER> (funcall gen) 2 CL-USER> (funcall gen) 3 CL-USER> (funcall gen) NIL CL-USER> (funcall gen) NIL Now, assume you are trying to permute a combinations of one or more of these closures. How would you implement a function that returns a new closure that subsequently creates a permutation of all closures contained within it? i.e.: (defun permute-closures (counters) ......) such that the following holds true: CL-USER> (defvar collection (permute-closures (list (make-counter 3) (make-counter 3)))) CL-USER> (funcall collection) (1 1) CL-USER> (funcall collection) (1 2) CL-USER> (funcall collection) (1 3) CL-USER> (funcall collection) (2 1) ... and so on. The way I had it designed originally was to add a 'pause' parameter to the initial counting lambda such that when iterating you can still call it and receive the old cached value if passed ":pause t", in hopes of making the permutation slightly cleaner. Also, while the example above is a simple list of two identical closures, the list can be an arbitrarily-complicated tree (which can be permuted in depth-first order, and the resulting permutation set would have the shape of the tree.). I had this implemented, but my solution wasn't very clean and am trying to poll how others would approach the problem. Thanks in advance.

    Read the article

  • Moving Computer Player in Xcode

    - by user1631497
    I am working on a 2d game using xcode and objective-c. I am trying to make my enemy player move left if I am left of him, until he is touching my character. The same will go when I am right of him. Basically just trying to get him to move towards me. But my code to do so is not working. So I have my code that says the following -(void)moveTowardsCharacter { enemyLeftTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(goEnemyLeft) userInfo:nil repeats:YES]; if (enemyLeftTimer == nil){ enemyLeftTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(goEnemyLeft) userInfo:nil repeats:YES]; } } -(IBAction)enemyStopLeft { if (CGRectIntersectsRect(bluebox.frame, redbox.frame)) { [enemyLeftTimer invalidate]; enemyLeftTimer = nil; } } -(void)goEnemyLeft { if (redbox.center.x + [self getRedboxWidthLeft] > bluebox.center.x + [self getBlueboxWidthRight]) { redbox.center = CGPointMake(redbox.center.x -5, redbox.center.y); } } So the first bit is saying for it to set up a timer to continue moving left. The next will stop the timer if my player(bluebox) and the Computer player(redbox) collide. Finally, the thing that actually tells it to go left, but only if the bluebox is left of the redbox. The getRedBoxWidth Left and getBlueBoxWidthRight are just voids that get, well, the left and right edges. If you could, please help try and solve this code. Thank You.

    Read the article

  • how to slove error when using thread?

    - by ChandreshKanetiya
    I have following error msg in console when using NSThread "Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now..." I have submit my sample code here - (void)viewDidLoad { appDeleg = (NewAshley_MedisonAppDelegate *)[[UIApplication sharedApplication] delegate]; [[self tblView1] setRowHeight:80.0]; [super viewDidLoad]; self.title = @"Under Ground"; [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; [NSThread detachNewThreadSelector:@selector(CallParser) toTarget:self withObject:nil]; } -(void)CallParser { Parsing *parsing = [[Parsing alloc] init]; [parsing DownloadAndParseUnderground]; [parsing release]; [self Update_View]; //[myIndicator stopAnimating]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; } here "DownloadAndParseUnderground" is the method of downloding data from the rss feed and -(void) Update_View{ [self.tblView1 reloadData]; } when Update_View method is called the tableView reload Data and in the cellForRowAtIndexPath create error and not display custom cell - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; CustomTableviewCell *cell = (CustomTableviewCell *) [tblView1 dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { [[NSBundle mainBundle] loadNibNamed:@"customCell" owner:self options:nil]; cell = objCustCell; objCustCell = nil; }

    Read the article

  • Rails - Update a single attribute : link with custom action or form with hidden fields?

    - by MrRuru
    Let's say I have a User model, with a facebook_uid field corresponding to the user's facebook id. I want to allow the user to unlink his facebook account. Do do so, I need to set this attribute to nil. I currently see 2 ways of doing this First way : create a custom action and link to it # app/controllers/users_controller.rb def unlink_facebook_account @user = User.find params[:id] # Authorization checks go here @user.facebook_uid = nil @user.save # Redirection go here end # config/routes.rb ressources :users do get 'unlink_fb', :on => :member, :as => unlink_fb end # in a view = link_to "Unlink your facebook account", unlink_fb_path(@user) Second way : create a form to the existing update action # app/views/user/_unlink_fb_form.html.haml = form_for @user, :method => "post" do |f| = f.hidden_field :facebook_uid, :value => nil = f.submit "Unlink Facebook account" I'm not a big fan of either way. In the first one, I have to add a new action for something that the update controller already can do. In the second one, I cannot set the facebook_uid to nil without customizing the update action, and I cannot have a link instead of a button without adding some javascript. Still, what would you recommend as the best and most elegant solution for this context? Did I miss a third alternative?

    Read the article

  • Why won't my UITableViewCell deselect and update its text?

    - by Josh
    I have a UITableView with a list of stories and a cell at the bottom that loads more stories. I am trying to make the "More Stories..." cell deselect and change its text to "Loading..." when clicked. I have searched all over the internet and all over stackoverflow and I cant figure out why my code isnt working right. Right now, when the "More Stories..." cell is clicked, it stays selected and doesnt ever change its text. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1]; if (storyIndex == [stories count]) { UITableViewCell *moreCell = [tableView dequeueReusableCellWithIdentifier:@"more"]; if (moreCell == nil) { moreCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"more"] autorelease]; } // Set up the cell moreCell.textLabel.text = @"Loading..."; [tableView deselectRowAtIndexPath:indexPath animated:YES]; [self moreStories]; } else { NSLog(@"%@",[[stories objectAtIndex: storyIndex] objectForKey: @"link"]); webViewController *webController; webController = [[webViewController alloc] initWithURLPassed:[[stories objectAtIndex: storyIndex] objectForKey: @"link"]]; [self.navigationController pushViewController:webController animated:YES]; [webController release]; webController =nil; self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:nil action:nil]; } }

    Read the article

  • how to clear a data in tableviewcell again start reload?

    - by Ios_learner
    i'm developing a bluetooth apps.1) I want to hide a tableview when i start the apps..after i pressed a action button i want to enable a tableview.. 2)if i again press a action button means tableviewcell clear the data and show empty before searching..give me an idea.. some of the code- - (IBAction)connectButtonTouched:(id)sender { [self.deviceTable reloadData]; self.connectButton.enabled = YES; [self.deviceTable reloadData]; peripheralManager = [[PeripheralManager alloc] init]; peripheralManager.delegate = self; [peripheralManager scanForPeripheralsAndConnect]; [self.deviceTable reloadData]; [NSTimer scheduledTimerWithTimeInterval:(float)5.0 target:self selector:@selector (connectionTimer:) userInfo:nil repeats:YES]; alert=[[UIAlertView alloc] initWithTitle:@"Bluetooth" message:@"Scanning" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; UIActivityIndicatorView *progress=[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)]; [alert addSubview:progress]; [progress startAnimating]; [alert show]; } tableview -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [device count]; } -(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]; } cell.textLabel.text=[device objectAtIndex:indexPath.row]; cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton; return cell; } TableView Delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath]; [self performSegueWithIdentifier:@"TableDetails" sender:tableView]; }

    Read the article

  • Time.new does not work as I would expect

    - by Marius Pop
    I am trying to generate some seed material. seed_array.each do |seed| Task.create(date: Date.new(2012,06,seed[1]), start_t: Time.new(2012,6,2,seed[2],seed[3]), end_t: Time.new(2012,6,2,seed[2] + 2,seed[3]), title: "#{seed[0]}") end Ultimately I will put random hours, minutes, seconds. The problem that I am facing is that instead of creating a time with the 2012-06-02 date it creates a time with a different date: 2000-01-01. I tested Time.new(2012,6,2,2,20,45) in rails console and it works as expected. When I am trying to seed my database however some voodo magic happens and I don't get the date I want. Any inputs are appreciated. Thank you! Update1: * [1m[36m (0.0ms)[0m [1mbegin transaction[0m [1m[35mSQL (0.5ms)[0m INSERT INTO "tasks" ("created_at", "date", "description", "end_t", "group_id", "start_t", "title", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["created_at", Tue, 03 Jul 2012 02:15:34 UTC +00:00], ["date", Thu, 07 Jun 2012], ["description", nil], ["end_t", 2012-06-02 10:02:00 -0400], ["group_id", nil], ["start_t", 2012-06-02 08:02:00 -0400], ["title", "99"], ["updated_at", Tue, 03 Jul 2012 02:15:34 UTC +00:00]] [1m[36m (2.3ms)[0m [1mcommit transaction * This is a small sample of the log. Update 2 Task id: 101, date: "2012-06-26", start_t: "2000-01-01 08:45:00", end_t: "2000-01-01 10:45:00", title: "1", description: nil, group_id: nil, created_at: "2012-07-03 02:15:33", updated_at: "2012-07-03 02:15:33" This is what shows up in rails console.

    Read the article

  • Timed selector never performed

    - by sudo rm -rf
    I've added an observer for my method: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeViewAfterUpdating) name:@"labelUpdatedShouldReturn" object:nil]; Then my relevant methods: -(void)closeViewAfterUpdating; { NSLog(@"Part 1 called"); [self performSelector:@selector(closeViewAfterUpdating2) withObject:nil afterDelay:2.0]; } -(void)closeViewAfterUpdating2; { NSLog(@"Part 2 called"); [self dismissModalViewControllerAnimated:YES]; } The only reason why I've split this method into two parts is so that I can have a delay before the method is fired. The problem is, the second method is never called. My NSLog output shows Part 1 called, but it never fires part 2. Any ideas? EDIT: I'm calling the notification from a background thread, does that make a difference by any chance? Here's how I'm creating my background thread: [NSThread detachNewThreadSelector:@selector(getWeather) toTarget:self withObject:nil]; and in getWeather I have: [[NSNotificationCenter defaultCenter] postNotificationName:@"updateZipLabel" object:textfield.text]; Also, calling: [self performSelector:@selector(closeViewAfterUpdating2) withObject:nil]; does work. EDITx2: I fixed it. Just needed to post the notification in my main thread and it worked just fine.

    Read the article

  • Trouble accessing Mutable array

    - by Jared Gross
    Im having trouble with my for loop where I am trying to index user names. I am able to separate my original array into individual objects but am not able to send the value to a new array that I need to reference later on. The value and count for userNames in my self.userNamesArray = userNames; line is correct. But right after that when I log self.userNamesArray, I get (null). Any tips cause I'm not completely sure I'm cheers! .h @property (nonatomic, copy) NSMutableArray *userNamesArray; .m - (void)viewWillAppear:(BOOL)animated { self.friendsRelation = [[PFUser currentUser] objectForKey:@"friendsRelation"]; PFQuery *query = [self.friendsRelation query]; [query orderByAscending:@"username"]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if (error) { NSLog(@"Error: %@ %@", error, [error userInfo]); } else { self.friends = objects; NSArray *users = [self.friends valueForKey:@"username"]; NSLog(@"username:%@", users); //Create an array of name wrappers and pass to the root view controller. NSMutableArray *userNames = [[NSMutableArray alloc] initWithCapacity:[self.friends count]]; for (NSString *user in users) { componentsSeparatedByCharactersInSet:charSet]; NSArray *nameComponents = [user componentsSeparatedByString:@" "]; UserNameWrapper *userNameWrapper = [[UserNameWrapper alloc] initWithUserName:nil nameComponents:nameComponents]; [userNames addObject:userNameWrapper]; } self.userNamesArray = userNames; NSLog(@"userNamesArray:%@",self.userNamesArray); [self.tableView reloadData]; } Here's the code where I need to reference the self.userNamesArray where again, it is comping up nil. - (void)setUserNamesArray:(NSMutableArray *)newDataArray { if (newDataArray != self.userNamesArray) { self.userNamesArray = [newDataArray mutableCopy]; if (self.userNamesArray == nil) { self.sectionsArray = nil; NSLog(@"user names empty"); } else { [self configureSections]; } } }

    Read the article

  • Nested modal view controller gives strange message under iOS6?

    - by user1840362
    I am presenting a modal view controller from another modal view controller, and this worked fine under all iOS versions prior to iOS6. But under iOS6 I am getting the following warning message in the emulator: Warning: Attempt to present <UINavigationController: 0x14e93680> on <UINavigationController: 0x9fc6b70> while a presentation is in progress! The modal view controller is not shown if this warning appears. Basically I am using code like this to show the modal view controller: WebAuthViewController *authController = [[WebAuthViewController alloc] initWithNibName:nil bundle:nil]; authController.challenge = challenge; authController.delegate = self; UINavigationController *aNavController = [[UINavigationController alloc] initWithRootViewController:authController]; [self presentModalViewController:aNavController animated:YES]; [aNavController release]; [authController release]; The view that is already shown is a UIWebView also shown in a modal view, like this: WebViewController *addController = [[WebViewController alloc] initWithNibName:nil bundle:nil]; addController.urlToLoad = [NSURL URLWithString:urlString]; addController.delegate = self; UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:addController]; navigationController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; [self presentModalViewController:navigationController animated:YES]; [navigationController release]; [addController release]; The apple docs still suggest that one is supposed to be able to stack navigation controllers like this, so I am at a loss to explain why this happens. Any hints?

    Read the article

  • Differentiate Between UITableView Editing States?

    - by Josh Kahane
    I have been looking at trying to differentiate between editing states in my UITableView. I need to call a method only when in editing mode after tapping the edit button, so when you get your cell slide in and you see the little circular delete icons but NOT when the user swipes to delete. Is there anyway I can differentiate between the two? Thanks. EDIT: Solution thanks to Rodrigo Both each cell and the entire tableview has an 'editing' BOOL value, so I loop through all the cells and if more than one of them is editing then we know the whole table is (the user tapped the edit button), however if only one is editing then we know that the user has swiped a cell, editing that individual one, this lets me deal with each editing state individually! - (void)setEditing:(BOOL)editing animated:(BOOL)animated { [super setEditing:editing animated:animated]; int i = 0; //When editing loop through cells and hide status image so it doesn't block delete controls. Fade back in when done editing. for (customGuestCell *cell in self.tableView.visibleCells) { if (cell.isEditing) { i += 1; } } if (i > 1) { for (customGuestCell *cell in self.tableView.visibleCells) { if (editing) { // loop through the visible cells and animate their imageViews [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.4]; cell.statusImg.alpha = 0; [UIView commitAnimations]; } } } else if (!editing) { for (customGuestCell *cell in self.tableView.visibleCells) { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.4]; cell.statusImg.alpha = 1.0; [UIView commitAnimations]; } } }

    Read the article

  • iPhone SDK Tableview Datasource singleton error

    - by mrburns05
    I basically followed apple "TheElements" sample and changed "PeriodicElements" .h & .m to my own "SortedItems" .h & .m During compile I get this error: "Undefined symbols: "_OBJC_CLASS_$_SortedItems", referenced from: __objc_classrefs__DATA@0 in SortedByNameTableDataSource.o ld: symbol(s) not found collect2: ld returned 1 exit status " here is my SortedItems.m file #import "SortedItems.h" #import "item.h" #import "MyAppDelegate.h" @interface SortedItems(mymethods) // these are private methods that outside classes need not use - (void)presortItemsByPhysicalState; - (void)presortItemInitialLetterIndexes; - (void)presortItemNamesForInitialLetter:(NSString *)aKey; - (void)presortItemsWithPhysicalState:(NSString *)state; - (NSArray *)presortItemsByNumber; - (NSArray *)presortItemsBySymbol; - (void)setupItemsArray; @end @implementation SortedItems @synthesize statesDictionary; @synthesize itemsDictionary; @synthesize nameIndexesDictionary; @synthesize itemNameIndexArray; @synthesize itemsSortedByNumber; @synthesize itemsSortedBySymbol; @synthesize itemPhysicalStatesArray; static SortedItems *sharedSortedItemsInstance = nil; + (SortedItems*)sharedSortedItems { @synchronized(self) { if (sharedSortedItemsInstance == nil) { [[self alloc] init]; // assignment not done here } } return sharedSortedItemsInstance; // note: Xcode (3.2) static analyzer will report this singleton as a false positive // '(Potential leak of an object allocated') } + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { if (sharedSortedItemsInstance == nil) { sharedSortedItemsInstance = [super allocWithZone:zone]; return sharedSortedItemsInstance; // assignment and return on first allocation } } return nil; //on subsequent allocation attempts return nil } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (unsigned)retainCount { return UINT_MAX; //denotes an object that cannot be released } - (void)release { //do nothing } - (id)autorelease { return self; } // setup the data collection - init { if (self = [super init]) { [self setupItemsArray]; } return self; } - (void)setupItemsArray { NSDictionary *eachItem; // create dictionaries that contain the arrays of Item data indexed by // name self.itemsDictionary = [NSMutableDictionary dictionary]; // physical state self.statesDictionary = [NSMutableDictionary dictionary]; // unique first characters (for the Name index table) self.nameIndexesDictionary = [NSMutableDictionary dictionary]; // create empty array entries in the states Dictionary or each physical state [statesDictionary setObject:[NSMutableArray array] forKey:@"Solid"]; [statesDictionary setObject:[NSMutableArray array] forKey:@"Liquid"]; [statesDictionary setObject:[NSMutableArray array] forKey:@"Gas"]; [statesDictionary setObject:[NSMutableArray array] forKey:@"Artificial"]; MyAppDelegate *ad = (MyAppDelegate *)[[UIApplication sharedApplication]delegate]; NSMutableArray *rawItemsArray = [[NSMutableArray alloc] init]; [rawItemsArray addObjectsFromArray:ad.items]; // iterate over the values in the raw Items dictionary for (eachItem in rawItemsArray) { // create an atomic Item instance for each Item *anItem = [[Item alloc] initWithDictionary:eachItem]; // store that item in the Items dictionary with the name as the key [itemsDictionary setObject:anItem forKey:anItem.title]; // add that Item to the appropriate array in the physical state dictionary [[statesDictionary objectForKey:anItem.acct] addObject:anItem]; // get the Item's initial letter NSString *firstLetter = [anItem.title substringToIndex:1]; NSMutableArray *existingArray; // if an array already exists in the name index dictionary // simply add the Item to it, otherwise create an array // and add it to the name index dictionary with the letter as the key if (existingArray = [nameIndexesDictionary valueForKey:firstLetter]) { [existingArray addObject:anItem]; } else { NSMutableArray *tempArray = [NSMutableArray array]; [nameIndexesDictionary setObject:tempArray forKey:firstLetter]; [tempArray addObject:anItem]; } // release the Item, it is held by the various collections [anItem release]; } // release the raw Item data [rawItemsArray release]; // create the dictionary containing the possible Item states // and presort the states data self.itemPhysicalStatesArray = [NSArray arrayWithObjects:@"something",@"somethingElse",@"whatever",@"stuff",nil]; [self presortItemsByPhysicalState]; // presort the dictionaries now // this could be done the first time they are requested instead [self presortItemInitialLetterIndexes]; self.itemsSortedByNumber = [self presortItemsByNumber]; self.itemsSortedBySymbol = [self presortItemsBySymbol]; } // return the array of Items for the requested physical state - (NSArray *)itemsWithPhysicalState:(NSString*)aState { return [statesDictionary objectForKey:aState]; } // presort each of the arrays for the physical states - (void)presortItemsByPhysicalState { for (NSString *stateKey in itemPhysicalStatesArray) { [self presortItemsWithPhysicalState:stateKey]; } } - (void)presortItemsWithPhysicalState:(NSString *)state { NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] ; NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor]; [[statesDictionary objectForKey:state] sortUsingDescriptors:descriptors]; [nameDescriptor release]; } // return an array of Items for an initial letter (ie A, B, C, ...) - (NSArray *)itemsWithInitialLetter:(NSString*)aKey { return [nameIndexesDictionary objectForKey:aKey]; } // presort the name index arrays so the items are in the correct order - (void)presortItemsInitialLetterIndexes { self.itemNameIndexArray = [[nameIndexesDictionary allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; for (NSString *eachNameIndex in itemNameIndexArray) { [self presortItemNamesForInitialLetter:eachNameIndex]; } } - (void)presortItemNamesForInitialLetter:(NSString *)aKey { NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] ; NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor]; [[nameIndexesDictionary objectForKey:aKey] sortUsingDescriptors:descriptors]; [nameDescriptor release]; } // presort the ItemsSortedByNumber array - (NSArray *)presortItemsByNumber { NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"acct" ascending:YES selector:@selector(compare:)] ; NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor]; NSArray *sortedItems = [[itemsDictionary allValues] sortedArrayUsingDescriptors:descriptors]; [nameDescriptor release]; return sortedItems; } // presort the itemsSortedBySymbol array - (NSArray *)presortItemsBySymbol { NSSortDescriptor *symbolDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] ; NSArray *descriptors = [NSArray arrayWithObject:symbolDescriptor]; NSArray *sortedItems = [[itemsDictionary allValues] sortedArrayUsingDescriptors:descriptors]; [symbolDescriptor release]; return sortedItems; } @end I followed the sample exactly - don't know where I went wrong. Here is my "SortedByNameTableDataSource.m" #import "SortedByNameTableDataSource.h" #import "SortedItems.h" #import "Item.h" #import "ItemCell.h" #import "GradientView.h" #import "UIColor-Expanded.h" #import "MyAppDelegate.h" @implementation SortedByNameTableDataSource - (NSString *)title { return @"Title"; } - (UITableViewStyle)tableViewStyle { return UITableViewStylePlain; }; // return the atomic element at the index - (Item *)itemForIndexPath:(NSIndexPath *)indexPath { return [[[SortedItems sharedSortedItems] itemsWithInitialLetter:[[[SortedItems sharedSortedItems] itemNameIndexArray] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]; } // UITableViewDataSource methods - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"ItemCell"; ItemCell *itemCell = (ItemCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (itemCell == nil) { itemCell = [[[ItemCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; itemCell = CGRectMake(0.0, 0.0, 320.0, ROW_HEIGHT); itemCell.backgroundView = [[[GradientView alloc] init] autorelease]; } itemCell.todo = [self itemForIndexPath:indexPath]; return itemCell; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // this table has multiple sections. One for each unique character that an element begins with // [A,B,C,D,E,F,G,H,I,K,L,M,N,O,P,R,S,T,U,V,X,Y,Z] // return the count of that array return [[[SortedItems sharedSortedItems] itemNameIndexArray] count]; } - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { // returns the array of section titles. There is one entry for each unique character that an element begins with // [A,B,C,D,E,F,G,H,I,K,L,M,N,O,P,R,S,T,U,V,X,Y,Z] return [[SortedItems sharedSortedItems] itemNameIndexArray]; } - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { return index; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // the section represents the initial letter of the element // return that letter NSString *initialLetter = [[[SortedItems sharedSortedItems] itemNameIndexArray] objectAtIndex:section]; // get the array of elements that begin with that letter NSArray *itemsWithInitialLetter = [[SortedItems sharedSortedItems] itemsWithInitialLetter:initialLetter]; // return the count return [itemsWithInitialLetter count]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { // this table has multiple sections. One for each unique character that an element begins with // [A,B,C,D,E,F,G,H,I,K,L,M,N,O,P,R,S,T,U,V,X,Y,Z] // return the letter that represents the requested section // this is actually a delegate method, but we forward the request to the datasource in the view controller return [[[SortedItems sharedSortedItems] itemNameIndexArray] objectAtIndex:section]; } @end

    Read the article

  • CoreData update problems

    - by kpower
    My app makes updates in background thread then saves context changes. And in main context there is a table view that works with NSFetchedResultsController. For some time updates work correctly, but then exception is thrown. To check this I've added NSLog(@"%@", [self.controller fetchedObjects]); to -controllerDidChangeContent:. Here is what I got: "<PRBattle: 0x6d30530> (entity: PRBattle; id: 0x6d319d0 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PRBattle/p2> ; data: {\n battleId = \"-1\";\n finishedAt = \"2012-11-06 11:37:36 +0000\";\n opponent = \"0x6d2f730 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PROpponent/p1>\";\n opponentScore = nil;\n score = nil;\n status = 4;\n})", "<PRBattle: 0x6d306f0> (entity: PRBattle; id: 0x6d319f0 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PRBattle/p1> ; data: {\n battleId = \"-1\";\n finishedAt = \"2012-11-06 11:37:36 +0000\";\n opponent = \"0x6d2ddb0 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PROpponent/p3>\";\n opponentScore = nil;\n score = nil;\n status = 4;\n})", "<PRBattle: 0x6d30830> (entity: PRBattle; id: 0x6d31650 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PRBattle/p11> ; data: <fault>)", "<PRBattle: 0x6d306b0> (entity: PRBattle; id: 0x6d319e0 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PRBattle/p5> ; data: {\n battleId = 325;\n finishedAt = nil;\n opponent = \"0x6d2f730 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PROpponent/p1>\";\n opponentScore = 91;\n score = 59;\n status = 3;\n})", "<PRBattle: 0x6d30730> (entity: PRBattle; id: 0x6d31a00 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PRBattle/p6> ; data: {\n battleId = 323;\n finishedAt = nil;\n opponent = \"0x6d2ddb0 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PROpponent/p3>\";\n opponentScore = 0;\n score = 0;\n status = 3;\n})", "<PRBattle: 0x6d307b0> (entity: PRBattle; id: 0x6d31630 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PRBattle/p9> ; data: {\n battleId = 370;\n finishedAt = \"2012-11-06 14:24:14 +0000\";\n opponent = \"0x79a8e90 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PROpponent/p2>\";\n opponentScore = 180;\n score = 180;\n status = 4;\n})", "<PRBattle: 0x6d307f0> (entity: PRBattle; id: 0x6d31640 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PRBattle/p10> ; data: {\n battleId = 309;\n finishedAt = \"2012-11-02 01:19:27 +0000\";\n opponent = \"0x79a8e90 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PROpponent/p2>\";\n opponentScore = 120;\n score = 240;\n status = 4;\n})", "<PRBattle: 0x6d30770> (entity: PRBattle; id: 0x6d31620 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PRBattle/p7> ; data: {\n battleId = 315;\n finishedAt = \"2012-11-02 02:26:24 +0000\";\n opponent = \"0x79a8e90 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PROpponent/p2>\";\n opponentScore = 119;\n score = 179;\n status = 4;\n})" ) Faulted object (0xe972610) here causes crash. I've logged data during update & before saving. This object is in updatedObjects only. Why can this method return "bad" object? (Moreover, during updates this object is affected almost each update. And only after some passes becomes "bad" one). P.S.: I use RestKit to manage CoreData. UPDATED: The exception was got, when I did smth. like this: for (PRBattle *battle in [self.controller fetchedObjects) { switch (battle.statusScalar) { case ... default: [battle willAccessValueForKey:nil]; NSAssert1(NO, @"Unexpected battle status found: %@", battle); } } The exception is on line with -willAccessValueForKey:. Scalar status for battle is enum, that is bind to integer values 1..4. I've mentioned all possible values in switch's cases (above default:). And the last one has break;. So this one is possible only when battle.statusScalar returns non-enum value. Status scalar implementation in PRBattle: - (PRBattleStatuses)statusScalar { [self willAccessValueForKey:@"statusScalar"]; PRBattleStatuses result = (PRBattleStatuses)[self.status integerValue]; [self didAccessValueForKey:@"statusScalar"]; return result; } And battle.status has validation rules: - min-value: 1 - max-value: 4 - default: no value And the last thing - debug log: objc[4664]: EXCEPTIONS: throwing 0x7d33f80 (object 0xe67d2a0, a _NSCoreDataException) objc[4664]: EXCEPTIONS: searching through frame [ip=0x97b401 sp=0xbfffd9b0] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: catch(id) objc[4664]: EXCEPTIONS: unwinding through frame [ip=0x97b401 sp=0xbfffd9b0] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: handling exception 0x7d33f60 at 0x97b79f objc[4664]: EXCEPTIONS: rethrowing current exception objc[4664]: EXCEPTIONS: searching through frame [ip=0x97b911 sp=0xbfffd9b0] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: searching through frame [ip=0x9ac8b7 sp=0xbfffdc20] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: searching through frame [ip=0x97ee80 sp=0xbfffdc40] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: searching through frame [ip=0x361d0 sp=0xbfffdc70] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: searching through frame [ip=0xa701d8 sp=0xbfffde10] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: catch(id) objc[4664]: EXCEPTIONS: unwinding through frame [ip=0x97b911 sp=0xbfffd9b0] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: finishing handler objc[4664]: EXCEPTIONS: searching through frame [ip=0x97b963 sp=0xbfffd9b0] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: searching through frame [ip=0x9ac8b7 sp=0xbfffdc20] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: searching through frame [ip=0x97ee80 sp=0xbfffdc40] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: searching through frame [ip=0x361d0 sp=0xbfffdc70] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: searching through frame [ip=0xa701d8 sp=0xbfffde10] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: catch(id) objc[4664]: EXCEPTIONS: unwinding through frame [ip=0x97b963 sp=0xbfffd9b0] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: unwinding through frame [ip=0x9ac8b7 sp=0xbfffdc20] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: unwinding through frame [ip=0x97ee80 sp=0xbfffdc40] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: unwinding through frame [ip=0x361d0 sp=0xbfffdc70] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: unwinding through frame [ip=0x3656f sp=0xbfffdc70] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: unwinding through frame [ip=0xa701d8 sp=0xbfffde10] for exception 0x7d33f60 objc[4664]: EXCEPTIONS: handling exception 0x7d33f60 at 0xa701f5 2012-11-07 13:37:55.463 TestApp[4664:fb03] CoreData: error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. CoreData could not fulfill a fault for '0x6d31650 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PRBattle/p10>' with userInfo { NSAffectedObjectsErrorKey = ( "<PRBattle: 0x6d30830> (entity: PRBattle; id: 0x6d31650 <x-coredata://882BD521-90CD-4682-B19A-000A4976E471/PRBattle/p10> ; data: <fault>)" ); }

    Read the article

  • Why is UITableView not reloading (even on the main thread)?

    - by radesix
    I have two programs that basically do the same thing. They read an XML feed and parse the elements. The design of both programs is to use an asynchronous NSURLConnection to get the data then to spawn a new thread to handle the parsing. As batches of 5 items are parsed it calls back to the main thread to reload the UITableView. My issue is it works fine in one program, but not the other. I know that the parsing is actually occuring on the background thread and I know that [tableView reloadData] is executing on the main thread; however, it doesn't reload the table until all parsing is complete. I'm stumped. As far as I can tell... both programs are structured exactly the same way. Here is some code from the app that isn't working correctly. - (void)startConnectionWithURL:(NSString *)feedURL feedList:(NSMutableArray *)list { self.feedList = list; // Use NSURLConnection to asynchronously download the data. This means the main thread will not be blocked - the // application will remain responsive to the user. // // IMPORTANT! The main thread of the application should never be blocked! Also, avoid synchronous network access on any thread. // NSURLRequest *feedURLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:feedURL]]; self.bloggerFeedConnection = [[[NSURLConnection alloc] initWithRequest:feedURLRequest delegate:self] autorelease]; // Test the validity of the connection object. The most likely reason for the connection object to be nil is a malformed // URL, which is a programmatic error easily detected during development. If the URL is more dynamic, then you should // implement a more flexible validation technique, and be able to both recover from errors and communicate problems // to the user in an unobtrusive manner. NSAssert(self.bloggerFeedConnection != nil, @"Failure to create URL connection."); // Start the status bar network activity indicator. We'll turn it off when the connection finishes or experiences an error. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { self.bloggerData = [NSMutableData data]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [bloggerData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { self.bloggerFeedConnection = nil; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; // Spawn a thread to fetch the link data so that the UI is not blocked while the application parses the XML data. // // IMPORTANT! - Don't access UIKit objects on secondary threads. // [NSThread detachNewThreadSelector:@selector(parseFeedData:) toTarget:self withObject:bloggerData]; // farkData will be retained by the thread until parseFarkData: has finished executing, so we no longer need // a reference to it in the main thread. self.bloggerData = nil; } If you read this from the top down you can see when the NSURLConnection is finished I detach a new thread and call parseFeedData. - (void)parseFeedData:(NSData *)data { // You must create a autorelease pool for all secondary threads. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; self.currentParseBatch = [NSMutableArray array]; self.currentParsedCharacterData = [NSMutableString string]; self.feedList = [NSMutableArray array]; // // It's also possible to have NSXMLParser download the data, by passing it a URL, but this is not desirable // because it gives less control over the network, particularly in responding to connection errors. // NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; [parser setDelegate:self]; [parser parse]; // depending on the total number of links parsed, the last batch might not have been a "full" batch, and thus // not been part of the regular batch transfer. So, we check the count of the array and, if necessary, send it to the main thread. if ([self.currentParseBatch count] > 0) { [self performSelectorOnMainThread:@selector(addLinksToList:) withObject:self.currentParseBatch waitUntilDone:NO]; } self.currentParseBatch = nil; self.currentParsedCharacterData = nil; [parser release]; [pool release]; } In the did end element delegate I check to see that 5 items have been parsed before calling the main thread to perform the update. - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:kItemElementName]) { [self.currentParseBatch addObject:self.currentItem]; parsedItemsCounter++; if (parsedItemsCounter % kSizeOfItemBatch == 0) { [self performSelectorOnMainThread:@selector(addLinksToList:) withObject:self.currentParseBatch waitUntilDone:NO]; self.currentParseBatch = [NSMutableArray array]; } } // Stop accumulating parsed character data. We won't start again until specific elements begin. accumulatingParsedCharacterData = NO; } - (void)addLinksToList:(NSMutableArray *)links { [self.feedList addObjectsFromArray:links]; // The table needs to be reloaded to reflect the new content of the list. if (self.viewDelegate != nil && [self.viewDelegate respondsToSelector:@selector(parser:didParseBatch:)]) { [self.viewDelegate parser:self didParseBatch:links]; } } Finally, the UIViewController delegate: - (void)parser:(XMLFeedParser *)parser didParseBatch:(NSMutableArray *)parsedBatch { NSLog(@"parser:didParseBatch:"); [self.selectedBlogger.feedList addObjectsFromArray:parsedBatch]; [self.tableView reloadData]; } If I write to the log when my view controller delegate fires to reload the table and when cellForRowAtIndexPath fires as it's rebuilding the table then the log looks something like this: parser:didParseBatch: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: parser:didParseBatch: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: parser:didParseBatch: parser:didParseBatch: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath Clearly, the tableView is not reloading when I tell it to every time. The log from the app that works correctly looks like this: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath

    Read the article

  • Sorting linked lists in Pascal

    - by user3712174
    I'm doing my final project for Informatics class and I can't get my sorting procedure to work. Have a look at my program, specifically the bolded part (some things are in Croatian. - if you need something translated, let me know): type pokazivac=^slog; slog=record prezime_ime:string[30]; redni_broj:string[2]; fakultet:string[50]; bodovi:integer; sljedeci:pokazivac; end; var pocetni, trenutni, prethodni:pokazivac; i:integer; procedure racunaj; var i,a,c:integer; b,d,e,f,g,h,j:real; begin write('Postotak bodova (u decimalnom zapisu) koje ucenik ostvaruje na temelju prosjeka ocjena - '); readln(e); e:=e*1000/4; write('Prosjek ocjena u prvom razredu : '); readln(f); f:=f/5*e; write('Prosjek ocjena u drugom razredu : '); readln(g); g:=g/5*e; write('Prosjek ocjena u trecem razredu : '); readln(h); h:=h/5*e; write('Prosjek ocjena u cetvrtom razredu : '); readln(j); j:=j/5*e; d:=f+g+h+j; write('Broj predmeta (ne racunajuci hrvatski jezik, strani jezik i matematiku) koju je ucenik/ca polagao na maturi - '); readln(a); write('Postotak rijesnosti ispita iz hrvatskog jezika te zatim maksimum bodova koje je ucenik/ca mogao ostvariti - '); readln(b); readln(c); d:=d+b*c; write('Postotak rijesnosti ispita iz stranog jezika te zatim maksimum bodova koje je ucenik/ca mogao ostvariti - '); readln(b); readln(c); d:=d+(b*c); write('Postotak rijesnosti ispita iz matematike te zatim maksimum bodova koje je ucenik/ca mogao ostvariti - '); readln(b); readln(c); d:=d+(b*c); for i:=1 to a do begin writeln('Postotak rijesnosti dodatnog predmeta te zatim maksimum bodova koje je ucenik/ca mogao ostvariti - '); readln(b); readln(c); d:=d+(b*c); end; d:=round(d); writeln('Vas broj bodova je: ', d:4:2); write('Za nastavak pritisnite ENTER..'); readln; end; procedure unos; begin new(trenutni); write('Redni broj ucenika - ');readln(trenutni^.redni_broj); write('Prezime i ime - ');readln(trenutni^.prezime_ime); write('Naziv fakultet - ');readln(trenutni^.fakultet); write('Bodovi - ');readln(trenutni^.bodovi); trenutni^.sljedeci:=pocetni; pocetni:=trenutni; end; procedure ispis; begin writeln(); writeln('Lista popisanih ucenika:'); writeln(); trenutni:=pocetni; while trenutni<>NIL do begin with trenutni^do begin writeln('IME: ',prezime_ime); writeln('FAKULTET: ',fakultet); writeln('BODOVI: ',bodovi); writeln(); end; trenutni:=trenutni^.sljedeci; end; writeln(); write('Za nastavak pritisnite ENTER..'); readln; end; procedure brisi; var s:string; begin trenutni:= pocetni; prethodni:=pocetni; write('Redni broj ucenika kojeg zelite izbrisati - '); readln(s); while trenutni<>NIL do begin if trenutni^.redni_broj=s then begin prethodni^.sljedeci:=trenutni^.sljedeci; dispose(trenutni); break; end; trenutni:=trenutni^.sljedeci; end; end; procedure izmjeni; var s:string; begin trenutni:=pocetni; write('Redni broj ucenika cije podatke zelite izmijeniti - '); readln(s); while trenutni<> NIL do begin if trenutni^.redni_broj=s then begin write(trenutni^.prezime_ime, ' - '); readln(trenutni^.prezime_ime); write(trenutni^.fakultet, ' - '); readln(trenutni^.fakultet); write(trenutni^.bodovi, ' - '); readln(trenutni^.bodovi); break; end; trenutni:=trenutni^.sljedeci; end; end; **procedure sortiraj; var t1,t2,t:pokazivac; begin t1:=pocetni; while t1 <> NIL do begin t2:=t1^.sljedeci; while t2<>NIL do if t2^.bodovi<t1^.bodovi then begin new(t); t^.redni_broj:=t1^.redni_broj; t^.prezime_ime:=t1^.prezime_ime; t^.fakultet:=t1^.fakultet; t^.bodovi:=t1^.bodovi; t1^.redni_broj:=t2^.redni_broj; t1^.prezime_ime:=t2^.prezime_ime; t1^.fakultet:=t2^.fakultet; t1^.bodovi:=t2^.bodovi; t2^.redni_broj:=t^.redni_broj; t2^.prezime_ime:=t^.prezime_ime; t2^.fakultet:=t^.fakultet; t2^.bodovi:=t^.bodovi; dispose(t); end; t2:=t2^.sljedeci; end; t1:=t1^.sljedeci; write('Za nastavak pritisnite ENTER..'); readln; end;** begin pocetni:=NIL; trenutni:=NIL; writeln('******************************************'); writeln('**********DOBRODOSLI U FAX-O-MAT**********'); writeln('******************************************'); repeat writeln('1 - Racunaj broj bodova'); writeln('2 - Dodaj ucenika'); writeln('3 - Brisi ucenika'); writeln('4 - Ispis liste'); writeln('5 - Izmjeni podatke'); writeln('6 - Sortiraj listu prema broju bodova'); writeln('0 - Kraj'); readln(i); case i of 1:racunaj; 2:unos; 3:brisi; 4:ispis; 5:izmjeni; 6:sortiraj; end; until i=0; end. Either it crashes with a fatal error, or when I press the number 6, nothing happens. The pointer keeps blinking and I can't enter any more numbers.

    Read the article

  • vim: remove previous code indentation and convert to another

    - by ramgorur
    I have a c project with multiple files (more than 100), the codes are written in Whitesmiths style, but I want to change them into K&R style indentation. Is it possible to do using vim in an automated way ? For example I have a emacs-lisp script to achieve this -- (progn (find-file "{}") (mark-whole-buffer) (setq indent-tabs-mode nil) (untabify (point-min) (point-max)) (indent-region (point-min) (point-max) nil) (save-buffer)) I was wondering if there is a similar trick that could be done with vim.

    Read the article

  • How to display custom view in UIActionSheet?

    - by 4thSpace
    I have a UIView with a date picker that I'd like to display in an action sheet. I'm using the following code: -(IBAction) button_click:(id)sender{ //UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"the title" delegate:nil cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Destructive" otherButtonTitles:@"other", nil]; UIActionSheet *sheet = [[UIActionSheet alloc] init]; ActionSheetController *actionSheet = [[ActionSheetController alloc] initWithNibName:@"ActionSheetView" bundle:nil]; [sheet addSubview:actionSheet.view]; [sheet showInView:self.view]; } What I get is a little bit of the top part of the new view coming up from the bottom and that's it. If I comment the two middle lines of code and uncomment the top part to display a regular action sheet, it works fine. Any ideas what I might be doing wrong?

    Read the article

  • Save image to camera roll with UIImageWriteToSavedPhotosAlbum

    - by Momeks
    Hi , i try to save a photo with a button to camera roll after user capture a picture with Camera , but i dont know why my picture doesn't save at photo library !! here is my code : -(IBAction)savePhoto{ UIImageWriteToSavedPhotosAlbum(img.image,nil, nil, nil); } -(IBAction)takePic { ipc = [[UIImagePickerController alloc]init]; ipc.delegate = self; ipc.sourceType = UIImagePickerControllerSourceTypeCamera; [self presentModalViewController:ipc animated:YES]; } - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { img.image = [[info objectForKey:UIImagePickerControllerOriginalImage]retain]; [[picker parentViewController]dismissModalViewControllerAnimated:YES]; [picker release]; } ipc is UIImagePickerController and img is UIIMageView what's my problem ?

    Read the article

  • Getting list of bluetooth devices nearby on iphone sdk

    - by Michael Cindric
    Hi Guys, I need to be able to search for all bluetooth devices nearby and just get there ids. I don't need to pair at all. I am using iphone 2.3 beta. Is this possible l have tried using GameKit and no luck does anyone know how to do this. BOOL result = NO; if (!session) { session = [[GKSession alloc] initWithSessionID:@"SCANNER" displayName:nil sessionMode:GKSessionModePeer]; self.session.delegate = self; [self.session setDataReceiveHandler:self withContext:nil]; self.session.available = YES; result = YES; } it dies on [self.session setDataReceiveHandler:self withContext:nil]; with the following error Scanner[42754:207] Error: 30500 -- Invalid parameter for -setDataReceiveHandler:withContext:. then ~ DNSServiceRegister callback: Ref=471fa40, Flags=2, ErrorType=0 name=00rusor1A..iPhone Simulator regtype=_q1eu29voete9jf._udp. domain=local.

    Read the article

  • UIView removeFromSuperView animation delay

    - by Mike
    I have a method which animates one of the subviews of UIWindow and then removes it from UIWindow using removeFromSuperview. But when I put removeFromSuperview after animation block, the animation never shows, because removeFromSuperview removes the UIView from UIWindow before the animation plays :-( How can I delay removeFromSuperview so the animation plays first, and then subview is removed? I tried [NSThread sleepForTimeInterval:1]; after animation block but that didn't have desired effect, because animation sleeps too for some reason. My code for this method: - (void) animateAndRemove { NSObject *mainWindow = [[UIApplication sharedApplication] keyWindow]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.8]; UIView *theView = nil; for (UIView *currentView in [mainWindow subviews]) { if (currentView.tag == 666) { currentView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.0]; theView = currentView; } } [UIView setAnimationTransition: UIViewAnimationTransitionNone forView:theView cache:YES]; [UIView commitAnimations]; //[NSThread sleepForTimeInterval:1]; [theView removeFromSuperview]; }

    Read the article

  • MPMoviePlayerContentPreloadDidFinishNotification does not fire [iPhone]

    - by JOKe
    I'm running into a problem with the MPMoviePlayerContentPreloadDidFinishNotification notification. I've regisered to recieve the MPMoviePlayerContentPreloadDidFinishNotification notification and MPMoviePlayerPlaybackDidFinishNotification but the first one never fires. Is this bug in Firmware OS 3.0 ? maybe fixed in 3.1 ? or ? Because my divice and similator is 3.0 maybe this is a bug ? My code : ... [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MovieDidLoad:) name:MPMoviePlayerContentPreloadDidFinishNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MovieDidLoad:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; ... -(void)MovieDidLoad:(NSNotification*)notification { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notification Listener" message:@"Notification Listener invoked" cancelButtonTitle:@"Ok dude!" otherButtonTitles:nil]; [alert show]; [alert release]; } The MPMoviePlayerPlaybackDidFinishNotification is always fired but MPMoviePlayerContentPreloadDidFinishNotification is never fired. Any ideas ?

    Read the article

  • nsthread in iphone xcode

    - by BibiBuBu
    Good Day! i want to use nsthreads in a project of xcode that will call a function which is for the network access and will check that if the network is there or not, so i need to have a thread which will execute after lets say 1 minutes to check the connectivity. and will continue run unless the app is closed. [NSThread detachNewThreadSelector:@selector(startTheBackgroundJob) toTarget:self withObject:nil]; startTheBackgroundJob NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // wait for 3 seconds before starting the thread, you don't have to do that. This is just an example how to stop the NSThread for some time [NSThread sleepForTimeInterval:5]; //[self performSelectorInBackground:@selector(checkNet) withObject:nil]; [self performSelectorOnMainThread:@selector(checkNet) withObject:nil waitUntilDone:YES]; [pool release]; it works only for the first time but not any other, i mean only 1 loop it makes can somebody help me in this regard. Thanks

    Read the article

  • Crash when trying to get NSManagedObject from NSFetchedResultsController after 25 objects?

    - by Jeremy
    Hey everyone, I'm relatively new to Core Data on iOS, but I think I've been getting better with it. I've been experiencing a bizarre crash, however, in one of my applications and have not been able to figure it out. I have approximately 40 objects in Core Data, presented in a UITableView. When tapping on a cell, a UIActionSheet appears, presenting the user with a UIActionSheet with options related to the cell that was selected. So that I can reference the selected object, I declare an NSIndexPath in my header called "lastSelection" and do the following when the UIActionSheet is presented: // Each cell has a tag based on its row number (i.e. first row has tag 0) lastSelection = [NSIndexPath indexPathForRow:[sender tag] inSection:0]; NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:lastSelection]; BOOL onDuty = [[managedObject valueForKey:@"onDuty"] boolValue]; UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Status" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; if(onDuty) { [actionSheet addButtonWithTitle:@"Off Duty"]; } else { [actionSheet addButtonWithTitle:@"On Duty"]; } actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque; // Override the typical UIActionSheet behavior by presenting it overlapping the sender's frame. This makes it more clear which cell is selected. CGRect senderFrame = [sender frame]; CGPoint point = CGPointMake(senderFrame.origin.x + (senderFrame.size.width / 2), senderFrame.origin.y + (senderFrame.size.height / 2)); CGRect popoverRect = CGRectMake(point.x, point.y, 1, 1); [actionSheet showFromRect:popoverRect inView:[sender superview] animated:NO]; [actionSheet release]; When the UIActionSheet is dismissed with a button, the following code is called: - (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex { // Set status based on UIActionSheet button pressed if(buttonIndex == -1) { return; } NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:lastSelection]; if([actionSheet.title isEqualToString:@"Status"]) { if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"On Duty"]) { [managedObject setValue:[NSNumber numberWithBool:YES] forKey:@"onDuty"]; [managedObject setValue:@"onDuty" forKey:@"status"]; } else { [managedObject setValue:[NSNumber numberWithBool:NO] forKey:@"onDuty"]; [managedObject setValue:@"offDuty" forKey:@"status"]; } } NSError *error; [self.managedObjectContext save:&error]; [tableView reloadData]; } This might not be the most efficient code (sorry, I'm new!), but it does work. That is, for the first 25 items in the list. Selecting the 26th item or beyond, the UIActionSheet will appear, but if it is dismissed with a button, I get a variety of errors, including any one of the following: [__NSCFArray section]: unrecognized selector sent to instance 0x4c6bf90 Program received signal: “EXC_BAD_ACCESS” [_NSObjectID_48_0 section]: unrecognized selector sent to instance 0x4c54710 [__NSArrayM section]: unrecognized selector sent to instance 0x4c619a0 [NSComparisonPredicate section]: unrecognized selector sent to instance 0x6088790 [NSKeyPathExpression section]: unrecognized selector sent to instance 0x4c18950 If I comment out NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:lastSelection]; it doesn't crash anymore, so I believe it has something do do with that. Can anyone offer any insight? Please let me know if I need to include any other information. Thanks! EDIT: Interestingly, my fetchedResultsController code returns a different object every time. Is this expected, or could this be a cause of my issue? The code looks like this: - (NSFetchedResultsController *)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:@"Employee" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Set the batch size to a suitable number. [fetchRequest setFetchBatchSize:80]; // Edit the sort key as appropriate. NSString *sortKey; BOOL ascending; if(sortControl.selectedSegmentIndex == 0) { sortKey = @"startTime"; ascending = YES; } else if(sortControl.selectedSegmentIndex == 1) { sortKey = @"name"; ascending = YES; } else { sortKey = @"onDuty"; ascending = NO; } NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:ascending]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Edit the section name key path and cache name if appropriate. NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; aFetchedResultsController.delegate = self; self.fetchedResultsController = aFetchedResultsController; [aFetchedResultsController release]; [fetchRequest release]; [sortDescriptor release]; [sortDescriptors release]; NSError *error = nil; if (![fetchedResultsController_ performFetch:&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(); } return fetchedResultsController_; } This happens when I set a breakpoint: (gdb) po [self fetchedResultsController] <NSFetchedResultsController: 0x61567c0> (gdb) po [self fetchedResultsController] <NSFetchedResultsController: 0x4c83630>

    Read the article

  • EXC_BAD_ACCESS due to PostNotification

    - by Sagar Mane
    Hello All, I am facing one issue regarding one module let me clear the flow for the same. I have one customized UITableviewCell. When I am getting some new information I am posting one notification [[NSNotificationCenter defaultCenter] postNotificationName:KGotSomething object:nil userInfo:message]; In view where I am maintaining the table I am initiating a customized cell - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { cell= [[CustomCell alloc] initWithFrame: reuseIdentifier:identifier document:doc]; return cell; } now in customcell.mm - (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(GotSomething:) name:KGotSomething object:nil]; } and in dealloc - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:KGotSomething object:nil]; } Now my app crashes due to this notification and dealloc is never get called. Can you guys help me, how to get this working or anything I m doing wrong over here... Thanks, Sagar

    Read the article

  • Changing color of the titlebar, background and text of MFMailComposeViewController

    - by iSharreth
    I am sending email from my iPhone application. Everything working fine, but I want to change the color of the title bar that appears from blue to black and the background color from white to black. Also, all the text to white color. What should I do? Anyone please help! I used the below code: (IBAction)sendMail{ MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc]init]; mailComposer.mailComposeDelegate = self; if([MFMailComposeViewController canSendMail]){ [mailComposer setToRecipients: [NSArray arrayWithObjects:@"[email protected]",nil]]; [mailComposer setSubject: nil]; [mailComposer setMessageBody: nil isHTML:NO]; [self presentModalViewController:mailComposer animated: YES]; }

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >