Posts

Post marked as unsolved
27 Views

UIGestureRecognizerStateEnded not getting registered upon ending of an object's rotation

I'm wanting to have the last "if" statement in the following code snippet, get processed when my object's rotation ends. (void)rotate:(UIRotationGestureRecognizer *)sender{ NSLog(@"Rotation- %@, iteration- %d", sender, n); if (sender.state== UIGestureRecognizerStateBegan) { NSLog(@"began- %f, iteration- %d", sender.rotation, n); } else if(sender.state== UIGestureRecognizerStateChanged){ NSLog(@"changed- %f, iteration- %d", sender.rotation, n); newRotation= sender.rotation; sender.view.transform= CGAffineTransformMakeRotation(newRotation); if(newRotation= 2*M_PI*n+2*M_PI){ n++; NSLog(@"current iteration- %d, rotation- %f, angle swept- %f", n, sender.rotation, 2*M_PI*n+2*M_PI); } } else if (sender.state== UIGestureRecognizerStateEnded){ NSLog(@"ended- %f", sender.rotation); In the above code, the first 2 "if" statements are getting registered when the object is made to begin to rotate (touch begins gesture) and when it actually undergoes rotation (changes in continuous touch gesture). This all happens when the "rotate" message is received by a UIRotationGestureRecognizer object. However, the third "if" statement (UIGestureRecognizerStateEnded) is, often, not getting registered when the same "rotate" message is passed upon the ending of rotation. In fact, it often works, only when I perform a separate touch gesture afterward so that the gesture state then changes from "UIGestureRecognizerStateBegan" to "UIGestureRecognizerStateEnded". My concern is that the transition from "UIGestureRecognizerStateChanged" to "UIGestureRecognizerStateEnded", often doesn't happen. Any useful suggestion or workaround to address this issue would be most welcome.
Asked
by Rahul88.
Last updated .
Post marked as unsolved
132 Views

UIView element not responding to touches once it moves, using CAAnimation, from its superview to an adjacent view

I have to perform an animation by making an interface element (UIView) move across the screen, so that the animation gives the appearance of the same moving from its superview over another view adjacent to its superview. @implementation MovableElement(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{     NSLog(@"%@", NSStringFromSelector(_cmd));     UITouch *t= [touches anyObject];     CGPoint p= [t locationInView:self]; &#9;&#9; a= [CABasicAnimation animationWithKeyPath:@"position"];     [a setFromValue:@(self.layer.position)];     [a setToValue:@(p)]; &#9;&#9;[self.layer addAnimation:a forKey:@"positionAnimation"]; } (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{     NSLog(@"%@", NSStringFromSelector(_cmd));     UITouch *t= [touches anyObject];     CGPoint p= [t locationInView:self];     [a setToValue:@(p)];     [self.layer setPosition:p]; }(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{     NSLog(@"%@", NSStringFromSelector(_cmd));     UITouch *t= [touches anyObject];     CGPoint p= [t locationInView:self]; &#9;&#9; self.layer.position= p; } @end The issue is that when the "MovableElement" object moves from its position, upon dragging it, away from its superview's position and on top of another view, it ends up not responding to touch events anymore. So that none of the above touch methods get called after this, anymore. And so, you cannot perform any animation after this stage; once the "MovableElement" has landed on another view, that is. I would like to know the reason behind this. I'm new to Core Animations and CALayers. Any suggestions would be most welcome. Thank you.
Asked
by Rahul88.
Last updated .
Post marked as solved
122 Views

Life of an NSStackBlock

I am trying to reproduce a scenario where I should be able to generate a runtime error, when I return an NSStackBlock from an objC method. Here is the code- ReturnedBlock.h #import <Foundation/Foundation.h> @interface Test: NSObject{ int a; }(int (^) (int, int))compute; @end ReturnedBlock.m @implementation Test(int (^) (int, int))compute{ &#9;NSLog(@"using the block"); &#9;int (^block)(int, int)=&#9;^int (int x, int y){ &#9;&#9;self; &#9;&#9;return x*y; &#9;}; &#9;return block; } int main(){ Test *testObj= [[Test alloc] init]; int&#9;(^receivedBlock)(int, int)= [testObj compute]; &#9;NSLog(@"%@", receivedBlock); &#9;NSLog(@"%d", receivedBlock(8, 9)); &#9;NSLog(@"%d", receivedBlock(8, 9)); /*This line should generate a seg fault*/ &#9;NSLog(@"%d", receivedBlock(8, 9)); } @end Console:- using the block Received Block- <NSStackBlock: 0x7ffee25eea20> 72 72 72 In the above code, The block is of stack type, and so is supposed to live in the current stack frame of the method "compute". So, upon returning that block from the method, how come it is able to outlive its current scope i.e the stack frame-"compute", that got popped off the callstack? Should this code be getting a seg fault or something, since the NSStackBlock dies as and when the current stack frame- "compute" gets popped off the callstack. In my view, the commented line of code is where there should be generation of run time error. But what is happening, is that the code is running each time I execute it.
Asked
by Rahul88.
Last updated .
Post marked as unsolved
270 Views

UIPopoverPresentationController not showing its contentViewcontroller's navigation items

I'm making use of UIPopoverPresentationController in order to present a UITableViewController as its contentViewController on an iPad. In the process, I have noticed that the contentViewController i.e UITableViewController is unable to present itself fully, in that the navigation items that it has, are not being shown. The 2 nav items are of type UIBarButtonItem, one for editing the rows of the tableView, and the other for adding a new row.Here is the code--(IBAction)showAssetTypePicker:(UIButton *)sender{ NSLog(@"AssetTypePicker button pressed!!"); assetTypePicker= [[AssetTypePicker alloc] init]; [self.view endEditing:YES]; NSLog(@"current item's assetType- %@",_item.assetType); [assetTypePicker setItem:_item]; /*Bronze Challenge*/ if ([[UIDevice currentDevice] userInterfaceIdiom]== UIUserInterfaceIdiomPad) { [assetTypePicker.tableView setDelegate:self];//Setting DetailViewController as UITableView's delegate assetTypePicker.modalPresentationStyle= UIModalPresentationPopover; [self presentViewController:assetTypePicker animated:YES completion:nil]; //Configuring the PopoverPresentationController assetTypePickerPopover= assetTypePicker.popoverPresentationController; NSLog(@"assetTypePickerPopover- %@",assetTypePickerPopover); [assetTypePickerPopover setDelegate:self]; assetTypePickerPopover.sourceView= sender; assetTypePickerPopover.sourceRect= sender.bounds; assetTypePickerPopover.permittedArrowDirections= UIPopoverArrowDirectionAny; } else{//..for iPhone [self.navigationController pushViewController:assetTypePicker animated:YES]; } } In the above code snippet, the AssetTypePicker is a UITableViewController which is to presented on both iPad and iPhone. For the iPhone, I have had it presented straightaway by pushing it onto an existing viewcontroller, and it takes effect when the user taps a UIButton. For the iPad, there is "assetTypePickerPopover" of type UIPopoverPresentationController, that is being used.The result is a popover that gets presented upon tapping of a UIButton, but without the UIBarButtonItems that constitute the navigation items of the AssetTypePicker.https://www.dropbox.com/s/5sfpat05m7un2pg/Screenshot%202019-11-03%20at%209.56.56%20PM.png?dl=0Whereas, on the iPhone, the navigation items are being shown as-https://www.dropbox.com/s/kjkrvbn7a7htgss/Screenshot%202019-11-07%20at%206.22.40%20PM.png?dl=0If anyone could advice on how to work through this, i'd be grateful.
Asked
by Rahul88.
Last updated .
Post marked as unsolved
258 Views

Coredata issue

I'm having trouble persisting data in order to mark some of the read rss feed links as favorites. The condition for favoriting an rss link is that the particular link should be read first. I have used core data in order to save the read links as well. Here is the code-BNRFeedStore.h#import #import @class RSSChannel; @class RSSItem; @interface BNRFeedStore : NSObject{ NSManagedObjectContext *context, *context2; NSManagedObjectModel *model; NSManagedObject *managedObject; } @property (nonatomic, strong) NSDate *topSongsCacheDate; +(BNRFeedStore *)sharedStore; -(RSSChannel *)fetchRSSFeedWithCompletion:(void (^)(RSSChannel *obj,NSError *error))block; -(void)fetchTopSongs:(int)count withCompletion:(void (^)(RSSChannel *obj, NSError *error))block; -(void)markItemAsRead:(RSSItem *)item; -(BOOL)hasItemBeenRead:(RSSItem *)item; -(void)markItemAsFavorite:(RSSItem *)item; -(BOOL)hasItemBeenFavorited:(RSSItem *)item; @endBNRFeedStore.m#import "BNRFeedStore.h" #import "RSSChannel.h" #import "BNRConnection.h" #import "RSSItem.h" @implementation BNRFeedStore //@synthesize topSongsCacheDate; -(void)markItemAsRead:(RSSItem *)item{ // if the item is already in Core Data, no need for duplicates if ([self hasItemBeenRead:item]) { return; } // create a new Link object and insert it into context // NSManagedObject *obj= [NSEntityDescription insertNewObjectForEntityForName:@"Link" inManagedObjectContext:context]; // Set the Link's urlString from the RSSItem [managedObject setValue:item.link forKey:@"urlString"]; // immediately save the changes [context save:nil]; } -(BOOL)hasItemBeenRead:(RSSItem *)item{ // create a request to fetch all Links with the same urlString as this item's link NSFetchRequest *req= [[NSFetchRequest alloc] initWithEntityName:@"Link"]; NSPredicate *pred= [NSPredicate predicateWithFormat:@"urlString like %@", item.link]; [req setPredicate:pred]; NSLog(@"predicate1- %@", req.predicate); // if there is at least one Link, then this has been read before NSArray *entries= [context executeFetchRequest:req error:nil]; NSLog(@"read entries- %@", entries); if (entries.count&gt;0) { NSLog(@"read entry- %@", entries[0]); return YES; } // if core data has never seen this link, then it hasn't been read return NO; } -(void)markItemAsFavorite:(RSSItem *)item{ if ([self hasItemBeenFavorited:item]) { return; } // create a new "Link" object and insert it into context // NSManagedObject *obj= [NSEntityDescription insertNewObjectForEntityForName:@"Link" inManagedObjectContext:context]; // Set the Link's urlString from the RSSItem [managedObject setValue:item.link forKey:@"favoritedURLString"]; [context save:nil]; } -(BOOL)hasItemBeenFavorited:(RSSItem *)item{ // create a request to fetch all Links with the same urlString as this item's link NSFetchRequest *req= [[NSFetchRequest alloc] initWithEntityName:@"Link"]; NSPredicate *pred= [NSPredicate predicateWithFormat:@"favoritedURLString like %@", item.link]; [req setPredicate:pred]; NSLog(@"predicate2- %@", req.predicate); // if there is at least one Link, then this has been favorited before NSArray *entries= [context executeFetchRequest:req error:nil]; NSLog(@"favorited entries- %@", entries); if (entries.count&gt;0) { NSLog(@"favorited entry- %@", entries[0]); return YES; } // if core data has never seen this link, then it hasn't been read return NO; } +(BNRFeedStore *)sharedStore{ static BNRFeedStore *feedStore=nil; if (!feedStore) { feedStore= [[BNRFeedStore alloc] init]; } return feedStore; } -(id)init{ if (self= [super init]) { model= [NSManagedObjectModel mergedModelFromBundles:nil]; NSPersistentStoreCoordinator *psc= [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; NSError *error= nil; NSString *dbPath= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; dbPath= [dbPath stringByAppendingPathComponent:@"read-feed.db"]; NSLog(@"%@",dbPath); NSURL *dbURL= [NSURL fileURLWithPath:dbPath]; if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dbURL options:nil error:&amp;error]){ NSLog(@"checking!"); [NSException raise:@"Open failed" format:@"Reason: %@",[error localizedDescription]]; } context= [[NSManagedObjectContext alloc] init]; [context setPersistentStoreCoordinator:psc]; [context setUndoManager:nil]; NSEntityDescription *entity= [[model entitiesByName] objectForKey:@"Link"]; managedObject= [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:context]; } return self; }In the above code of my Store-Object, attempting to persist the changes made to a read item by favoriting it, has been unsuccessful. All the changes, whether "read or favorited" status, are supposed to be stored in one "read-feed.db" file residing in the Documents directory of the app bundle. The changes made to the tableviewcell by checkmarking them as read, is getting persisted successfully, though. The problem is with favoriting those same read links. Every time I favorite a cell, the changes made do not even persist when the tableView undergoes reloading, let alone a new run session. I'll be able to provide additional source code of other files as well, should someone ask for it.Kindly advice.
Asked
by Rahul88.
Last updated .
Post marked as solved
336 Views

objective C memory management issue

I was just going over a piece of code the other day and then ended up compiling and running it. The result outputted on the console surprised me a bit. Here is the code-#import @interface TestObject: NSObject { int x; } @property TestObject *testObj; -(void)run; @end @implementation TestObject @synthesize testObj; -(void)run{ NSLog(@"running"); TestObject *obj= [[TestObject alloc] init]; testObj= obj; obj= nil; NSLog(@"testObj- %@", testObj); [testObj testLog]; NSLog(@"testObj now- %@", testObj); } -(void)testLog{ NSLog(@"test successful with %@", testObj); } -(void)dealloc{ NSLog(@"dealloc"); } @end int main(int argc, const char * argv[]) { TestObject *test= [[TestObject alloc] init]; [test run]; NSLog(@"testObj in the end- %@", test.testObj); [test.testObj testLog]; }And here is the output-2019-06-02 23:49:18.224 objcmemmanage[8869:288642] running2019-06-02 23:49:18.224 objcmemmanage[8869:288642] testObj- &lt;TestObject: 0x7f913e501100&gt;2019-06-02 23:49:18.224 objcmemmanage[8869:288642] test successful with (null)2019-06-02 23:49:18.224 objcmemmanage[8869:288642] testObj now- &lt;TestObject: 0x7f913e501100&gt;2019-06-02 23:49:18.224 objcmemmanage[8869:288642] testObj in the end- &lt;TestObject: 0x7f913e501100&gt;2019-06-02 23:49:18.224 objcmemmanage[8869:288642] test successful with (null)The output, in the 3rd line, says that the testObj has been deallocated. How come it is deallocated when the testObj receives the testLog message?? The local object pointer- "obj" is assigned to testObj and then is nil-ed in the next line. But, since we are using ARC, shouldn't testObj, which happens to also be an ivar, continue owning the TestObject from that point on? My understanding has been that ARC, during compilation, places in the necessary memory management code with retain and release messages being appropriately sent to the relevant object. The same behavior is observed through the 6th line of console's output. Before the control reaches the "testLog" message line, in both the cases, the TestObject created in the "run" method is kept alive up to that point. Then why dealloc it pre-maturely? This is what I want to happen during compilation while ARC works its magic--(void)run{....TestObject *obj= [[TestObject alloc] init];testObj= obj;[testObj retain]; //ARC's work. By now, retainCount ups to 2.obj= nil;......}What is happening here, behind the scenes, that I'm missing?
Asked
by Rahul88.
Last updated .
Post marked as solved
1.2k Views

NSXMLParser not delegating parsing task properly to its delegate

I'm building an RSSfeed reader wherein there the task of parsing the xmldata gets delegated to two separate objects. As the xml tree is walked down, the actual parsing task is initiated with the RSSContent object, where the title of individual articles is generated by picking up appropriate strings of characters, and then moved to RSSContentArticle object, where the web links to the actual articles are pieced together character by character.The job of delegation starts when the connection to the RSSfeed's webservice is established, and one ListViewController object is made a delegate of the NSXMLParser object. As the control flow reaches specific XML tags of interest, the job of parsing gets re-delegated to the next object, for instance- ListViewController-&gt;RSSContent-&gt;RSSContentArticle, and then gets moved back to the previous delegate as we keeping walking out of the nested element tags, one element at a time, like this- RSSContentArticle-&gt;RSSContent-&gt;ListViewController.However, I'm currently facing a problem while trying to achieve this flow of parsing as I want to have it move from RSSContent to RSSContentArticle through re-delegation.Here is the code-ListViewController.h#import @class RSSChannel, WebViewController, RSSContent; @interface ListViewController : UITableViewController&lt;nsxmlparserdelegate,uitableviewdelegate, uitableviewdatasource,="" nsurlconnectiondatadelegate=""&gt; { NSURLConnection *connection; NSMutableData *xmlData; RSSChannel *channel; NSMutableArray *contentCollection; NSMutableString *currentString; } @property (nonatomic, strong) WebViewController *webViewController; @property (nonatomic, strong) RSSContent *content; @property (nonatomic, strong) NSMutableString *cellTitle; -(void)fetchEntries; @endListViewController.m#import "ListViewController.h" #import "RSSContent.h" #import "RSSChannel.h" #import "RSSContentArticle.h" #import "RSSItem.h" #import "WebViewController.h" @interface ListViewController () @end @implementation ListViewController @synthesize webViewController, content; -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)io{ if ([[UIDevice currentDevice] userInterfaceIdiom]== UIUserInterfaceIdiomPad) { return YES; } return io== UIInterfaceOrientationPortrait; } - (id)initWithStyle:(UITableViewStyle)style { self = [super initWithStyle:style]; if (self) { // Custom initialization NSLog(@"ListViewcontroller init..%@ %@", self.tableView.dataSource, self.tableView.delegate); [self fetchEntries]; contentCollection= [[NSMutableArray alloc] init]; } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Uncomment the following line to preserve selection between presentations. // self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; } -(void)fetchEntries{ NSLog(@"%@", NSStringFromSelector(_cmd)); xmlData= [[NSMutableData alloc] init]; NSURL *url= [NSURL URLWithString:@"https://www.apple.com/pr/feeds/pr.rss"]; NSURLRequest *req= [NSURLRequest requestWithURL:url]; connection= [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];//self has been made NSURLConnection's delegate } -(void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data{ NSLog(@"%@", NSStringFromSelector(_cmd)); // Add the incoming chunk of data to the container we are keeping // The data always comes in the correct order [xmlData appendData:data]; } -(void)connectionDidFinishLoading:(NSURLConnection *)conn{ NSLog(@"%@", NSStringFromSelector(_cmd)); // We are just checking to make sure we are getting the XML NSString *xmlCheck= [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding]; NSLog(@"xmlCheck= %@",xmlCheck); NSXMLParser *parser=[[NSXMLParser alloc] initWithData:xmlData]; [parser setDelegate:self]; NSLog(@"parsing initiated"); [parser parse]; xmlData=nil; connection=nil; [self.tableView reloadData]; WSLog(@"channel test- %@\n %@\n %@\n",channel, [channel title], [channel infoString]); } -(void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error{ connection=nil; xmlData=nil; NSString *errorString= [NSString stringWithFormat:@"Fetch failed: %@",[error localizedDescription]]; UIAlertView *av= [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [av show]; } -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ NSLog(@"%@ found a %@ element", self, elementName); if ([elementName isEqual:@"channel"]) { // element starts // If the parser saw a channel, create a new object, have the ivar- 'channel' point to it. channel= [[RSSChannel alloc] init]; // Give the channel object a pointer back to ourselves for later. channel.parentParserDelegate= self; // Set the parser's delegate to the channel object // There will be a warning here, ignore it for now parser.delegate= channel; } else if ([elementName isEqual:@"entry"]) { content= [[RSSContent alloc] init]; // Give the content object a pointer back to ourselves for later. content.parentParserDelegate= self; parser.delegate= content; [contentCollection addObject:content]; } }RSSContent.h#import @class RSSContentArticle; @interface RSSContent : NSObject { NSMutableString *currentString; } @property (nonatomic, weak)id parentParserDelegate; @property (nonatomic, strong)NSString *title; @property (nonatomic, strong)NSString *link; @property (nonatomic, strong)RSSContentArticle *article; @endRSSContent.m#import "RSSContent.h" #import "RSSContentArticle.h" @implementation RSSContent @synthesize parentParserDelegate, title, link, article; -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ NSLog(@"\t%@ found a %@ element",self,elementName); if ([elementName isEqual:@"title"]) { currentString= [[NSMutableString alloc] init]; title= currentString; } else if([elementName isEqual:@"content"]){ article= [[RSSContentArticle alloc] init]; parser.delegate= article; article.parentParserDelegate= self; } } -(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock{ NSString *string= [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding]; NSLog(@"\tfound CDATA within content- %@",string); [currentString appendString:string]; } -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ NSLog(@"\tcontent ended"); currentString= nil; if ([elementName isEqual:@"entry"]) { parser.delegate= parentParserDelegate; } } @endRSSContentArticle.h#import @interface RSSContentArticle : NSObject { NSMutableString *currentString; } @property (nonatomic, weak)id parentParserDelegate; @property (nonatomic, strong)NSString *link; @endRSSContentArticle.m#import "RSSContentArticle.h" @implementation RSSContentArticle @synthesize link, parentParserDelegate; -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ NSLog(@"\t\t%@ found a %@ element",self,elementName); if ([elementName isEqual:@"a"]) { currentString= [[NSMutableString alloc] init]; link= currentString; } } -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ NSLog(@"\t\tfound character(s) within contentArticle- %@",string); [currentString appendString:string]; NSLog(@"\t\tcurrentString- %@", currentString); } -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ NSLog(@"\t\tcontent ended"); currentString= nil; if ([elementName isEqual:@"content"]) { parser.delegate= parentParserDelegate; } } @endWhen the code runs, the control does not flow through -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary&lt;NSString *,NSString *&gt; *)attributeDict in RSSContentArticle.m, meaning that the RSSContentArticle object does not get sent this message after the NSXMLParser having re-delegated parsing to the same in RSSContent.m file when the element name is "content". I have remained stuck with the issue for a while now. Can someone please look into this, advice me meaningfully on how to go about solving this issue. I'd be thankful.
Asked
by Rahul88.
Last updated .
Post marked as solved
1.1k Views

tableview being unable to reload data

I reviewing an old RSS reader project wherein the data is fetched from Apple press release website. The titles of the individual articles are to be the populated into the individual table cells controlled by a ListViewController. The Detail view (Web view in my case, controlled by WebViewController) will show the detailed article based on the selected title from the corresponding cell.Here is the code:-ListViewController.h#import @class RSSChannel, WebViewController, RSSContent; @interface ListViewController : UITableViewController&lt;nsxmlparserdelegate,uitableviewdelegate, uitableviewdatasource,="" nsurlconnectiondatadelegate=""&gt; { NSURLConnection *connection; NSMutableData *xmlData; RSSChannel *channel; NSMutableArray *contentCollection; } @property (nonatomic, strong) WebViewController *webViewController; @property RSSContent *content; -(void)fetchEntries; @endListViewController.m//// ListViewController.m// Nerdfeed/// Created by Rahul Agarwal on 16/09/1// Copyright (c) 2014 Rahul Agarwal. All rights reserved. #import "ListViewController.h" #import "RSSContent.h" #import "RSSChannel.h" #import "RSSItem.h" #import "WebViewController.h" @interface ListViewController () @end @implementation ListViewController @synthesize webViewController, content; -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)io{ if ([[UIDevice currentDevice] userInterfaceIdiom]== UIUserInterfaceIdiomPad) { return YES; } return io== UIInterfaceOrientationPortrait; } - (id)initWithStyle:(UITableViewStyle)style { self = [super initWithStyle:style]; if (self) { // Custom initialization NSLog(@"ListViewcontroller init..%@", self.tableView.dataSource); [self fetchEntries]; contentCollection= [[NSMutableArray alloc] init]; } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Uncomment the following line to preserve selection between presentations. // self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; } -(void)fetchEntries{ NSLog(@"%@", NSStringFromSelector(_cmd)); xmlData= [[NSMutableData alloc] init]; NSURL *url= [NSURL URLWithString:@"https://www.apple.com/pr/feeds/pr.rss"]; NSURLRequest *req= [NSURLRequest requestWithURL:url]; connection= [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];//self has been made NSURLConnection's delegate } -(void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data{ NSLog(@"%@", NSStringFromSelector(_cmd)); // Add the incoming chunk of data to the container we are keeping // The data always comes in the correct order [xmlData appendData:data]; } -(void)connectionDidFinishLoading:(NSURLConnection *)conn{ NSLog(@"%@", NSStringFromSelector(_cmd)); // We are just checking to make sure we are getting the XML NSString *xmlCheck= [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding]; // NSLog(@"xmlCheck= %@",xmlCheck); NSXMLParser *parser=[[NSXMLParser alloc] initWithData:xmlData]; [parser setDelegate:self]; NSLog(@"parsing initiated"); [parser parse]; xmlData=nil; connection=nil; [self.tableView reloadData]; WSLog(@"channel test- %@\n %@\n %@\n",channel, [channel title], [channel infoString]); } -(void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error{ connection=nil; xmlData=nil; NSString *errorString= [NSString stringWithFormat:@"Fetch failed: %@",[error localizedDescription]]; UIAlertView *av= [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [av show]; } -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ NSLog(@"%@ found a %@ element", self, elementName); if ([elementName isEqual:@"channel"]) { // element starts // If the parser saw a channel, create a new object, have the ivar- 'channel' point to it. channel= [[RSSChannel alloc] init]; // Give the channel object a pointer back to ourselves for later. channel.parentParserDelegate= self; // Set the parser's delegate to the channel object // There will be a warning here, ignore it for now parser.delegate= channel; } else if ([elementName isEqual:@"title"]) { content= [[RSSContent alloc] init]; // Give the content object a pointer back to ourselves for later. content.parentParserDelegate= self; parser.delegate= content; [contentCollection addObject:content]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 0; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSLog(@"no. of rows- %d", (int)contentCollection.count); //#warning Incomplete method implementation. // Return the number of rows in the section. // return [[channel items] count]; return contentCollection.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"Cell no.- %d", (int)indexPath.row); static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell==nil) { cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } // RSSContent *content= contentCollection[indexPath.row]; cell.textLabel.text= content.title; NSLog(@"cell title- %@", cell.textLabel.text); return cell; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ // Push the web view controller onto the navigation stack- this implicitly creates the web view controller's view the time through NSLog(@"Tableview- %@ %@", self.tableView, tableView); [[self navigationController] pushViewController:webViewController animated:YES]; // Grab the selected item RSSItem *entry= [channel.items objectAtIndex:indexPath.row]; // Construct a URL with the link string of the selected item NSURL *url= [NSURL URLWithString:entry.link]; // Construct a request-object with that URL NSURLRequest *req= [NSURLRequest requestWithURL:url]; // Load the request into the webView [webViewController.webView loadRequest:req]; // Set the title of the web view controller's navigation item [[webViewController navigationItem] setTitle:entry.title]; } @endThe above code basically performs the task of establishing connection, sending a URL request to the webserver, retrieving data in the form of XML, and having NSXMLParser delegate to the ListViewController the job of parsing that data tag by tag. The ListViewController then further divides the task of having NSXMLParser delegate the duty of parsing specific type of content, character by character, to RSSContent. In the interface file on the top, there are a couple of other forward declarations- RSSChannels, RSSItems. These are to be ignored for the purpose of this discussion.Here is the code for RSSContentRSSContent.h#import @interface RSSContent : NSObject { NSMutableString *currentString; } @property (nonatomic, weak)id parentParserDelegate; @property (nonatomic, strong)NSString *title; @endRSSContent.m#import "RSSContent.h" @implementation RSSContent @synthesize parentParserDelegate, title; -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ NSLog(@"parser did start element"); if ([elementName isEqual:@"![CDATA["]) { currentString= [[NSMutableString alloc] init]; title= currentString; } } -(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock{ NSString *string= [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding]; NSLog(@"\tfound CDATA within content- %@",string); currentString= [[NSMutableString alloc] init]; title= currentString; [currentString appendString:string]; } -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ NSLog(@"\tfound character(s) within content- %@",string); [currentString appendString:string]; } -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ NSLog(@"\tcontent ended"); currentString= nil; if ([elementName isEqual:@"title"]) { parser.delegate= parentParserDelegate; } } @endIn the code above, Im having RSSContent delegated the job of parsing the XML data , character by character, under the element name "title".There is a back-pointer (parentParserDelegate) that RSSContent uses, to redirect the delegation flow to the ListViewController. The problem at this point is that, I'm getting blank cells when running the app. This is understandable since none of the UITableViewDataSource methods are getting called here. The reloadData message has been sent once, by one of the NSURLConnectionDataDelegate methods in the ListViewController.m file. What I cannot figure is when and where to send the reloadData message to the tableView. Pls advice. Any suggestions or tips given, could help me. Thank you
Asked
by Rahul88.
Last updated .
Post marked as unsolved
330 Views

mkmapview not scaling to iPad's view

I have a project that makes use of MKMapView, that works fine on an iphone. But when i run it on an ipad simulator or actual ipad, the MKMapView does not scale to cover its view. It retains the iPhone's viewscale.Here is what it looks like on an iPhone- https://www.dropbox.com/s/gvsu6dda4x2o3de/Screen%20Shot%202018-07-28%20at%205.59.45%20PM.png?dl=0And here is what it looks like on an iPad-https://www.dropbox.com/s/jc6q86rzyodf011/Screen%20Shot%202018-07-28%20at%206.01.05%20PM.png?dl=0I have universalized the project from the project settings. What am I missing here. Any advice would be helpful. Thank you
Asked
by Rahul88.
Last updated .
Post marked as solved
1.8k Views

Correct way to declare Global vars

I recently came across a piece of obj-C code that looked something like this:-#import "LocationSeeker.h" @interface LocationSeeker () @end NSString *const LocationSeekerMapTypePrefKey= @"LocationSeekerMapTypePrefKey"; NSString *const CenterCoordinateLatitudePrefKey= @"CenterCoordinateLatitudePrefKey"; NSString *const CenterCoordinateLongitudePrefKey= @"CenterCoordinateLongitudePrefKey"; @implementation LocationSeeker +(void)initialize{//used for making factory settings NSLog(@"initializing custom factory settings"); //THE factory settings are not saved to disk.. These effect at runtime.. NSMutableDictionary *defaults= [NSMutableDictionary dictionary]; //Setting the default as Hybrid view for map ...... } -(IBAction)buttonDidGetPressed:(id)sender{ NSLog(@"%@",NSStringFromSelector(_cmd)); NSLog(@"%@",sender); [[NSUserDefaults standardUserDefaults] setInteger:[sender selectedSegmentIndex] forKey:WhereamiMapTypePrefKey]; if([sender selectedSegmentIndex]==0){ [worldView setMapType:MKMapTypeStandard]; }........ ..... } In the code above, there are 3 constants declared at a global level. What i wanted to inquire was whether this is the correct place to declare and define globals. Shouldn't these be declared and defined inside @implementation LocationSeeker ? Like this:#import "LocationSeeker.h" @interface LocationSeeker () @end @implementation LocationSeeker NSString *const LocationSeekerMapTypePrefKey= @"LocationSeekerMapTypePrefKey"; NSString *const CenterCoordinateLatitudePrefKey= @"CenterCoordinateLatitudePrefKey"; NSString *const CenterCoordinateLongitudePrefKey= @"CenterCoordinateLongitudePrefKey"; +(void)initialize{//used for making factory settings NSLog(@"initializing custom factory settings"); //THE factory settings are not saved to disk.. These effect at runtime.. NSMutableDictionary *defaults= [NSMutableDictionary dictionary]; //Setting the default as Hybrid view for map ...... }What are the effects of the difference between the 2 approaches?
Asked
by Rahul88.
Last updated .
Post marked as solved
893 Views

UIStepper not being able to register tapping.

I have a UIStepper object added to a custom tableviewcell. There is a label below it on the cell too. I need the label to display value changes, in accordance with the manipulation done through the UIStepper. The problem I facing though is that when i run the project and the interface displays on the simulator, I'm unable to make stepper register taps when i click on the "plus" or the "minus" button. Even the related IBAction does not log into the console. I have not hooked all the objects to their appropriate ivars in the interface file properly. I have tried diagnosing the problem. But it was to no avail. Kindly advise, anyone.Here is the IBAction code:-- (IBAction)changeItemValueWith:(UIStepper *)sender { NSLog(@"%@",NSStringFromSelector(_cmd)); NSString *selectorString= NSStringFromSelector(_cmd); selectorString= [selectorString stringByAppendingString:@"havingValue:"]; SEL selector= NSSelectorFromString(selectorString); [self sendAction:selector withObject:sender withObject:valueLabel toController:controller]; }I can provide with more details of the interface settings.
Asked
by Rahul88.
Last updated .
Post marked as unsolved
1k Views

"takePicture" method not facilitating generation of shot image

In a project that im designing, i'm facing a problem with adding a camera-shot image onto an image view. I am using an uiimagepickercontroller which has been given an overlayview placed alongside some camera barbuttonitems to form a custom cameraview. In order to carry out the actual taking of pictures or canceling the operation, i have added custom actions- shootPicture and cancelShootingOfPicture.Here is the code:-DetailViewController.h#import &lt;UIKit/UIKit.h&gt; @class BNRItem; @interface DetailViewController : UIViewController&lt;UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate&gt; { __weak IBOutlet UITextField *nameField; __weak IBOutlet UITextField *serialNumberField; __weak IBOutlet UITextField *valueField; __weak IBOutlet UILabel *dateLabel; __weak IBOutlet UIImageView *imageView; __weak IBOutlet UIBarButtonItem *clearButton; UIImagePickerController *imagePicker; } @property (setter = setItem:)BNRItem *item; - (IBAction)takePicture:(id)sender; - (IBAction)clearImage:(id)sender; - (IBAction)backgroundTapped:(id)sender; @endDetailViewController.m@implementation DetailViewController @synthesize item; -(void)viewDidLoad{ NSLog(@"DetailView loaded"); NSLog(@"DetailView- %@", self.view); NSLog(@"%@",self.view.subviews); [super viewDidLoad]; [[self view] setBackgroundColor:[UIColor groupTableViewBackgroundColor]]; } - (IBAction)takePicture:(id)sender { //custom action to present imagepickercolller's view on top of DetailView NSLog(@"Camera button tapped"); imagePicker= [[UIImagePickerController alloc] init]; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { / Setting up a camera view */ UIToolbar *cameratoolbar= [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-60, self.view.frame.size.width, 60)]; NSArray *cameraButtons= @[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(shootPicture)], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelShootingOfPicture)]]; [cameratoolbar setItems:cameraButtons]; OverlayView *overlayView= [[OverlayView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-60)]; UIView *cameraView= [[UIView alloc] initWithFrame:self.view.bounds]; [cameraView addSubview:overlayView]; [cameraView addSubview:cameratoolbar]; NSLog(@"Yes. The Camera is available. Start"); [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera]; imagePicker.cameraOverlayView= cameraView; imagePicker.showsCameraControls= NO; NSLog(@"current camera overlay- %@", imagePicker.cameraOverlayView); } else{ NSLog(@"The Camera isn't available. Try thru the Photo Library now"); [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary] ; } imagePicker.allowsEditing=YES;/ [imagePicker setDelegate:self]; NSLog(@"Presenting Modal Controller- %@",imagePicker); [self presentViewController:imagePicker animated:YES completion:NULL]; } -(void)shootPicture{ //custom action to capture a shot. [imagePicker takePicture]; //I am to believe this method internally sends "imagePickerController: didFinish..." message to the delegate- DetailViewController. } -(void)cancelShootingOfPicture{ //custom action [imagePicker dismissViewControllerAnimated:YES completion:nil]; } -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ NSLog(@"image selected from imagePicker- %@",picker); NSString *oldKey= item.imageKey; if (oldKey) { // Since we are to generate a new key, deleting old-key for the same "BNRItem" is sensible to do. NSLog(@"Deleting image having key- %@",oldKey); [[BNRImageStore sharedStore] deleteImageForKey:oldKey]; } UIImage *image= [info objectForKey:UIImagePickerControllerEditedImage]; NSLog(@"shot image- %@", image); //ISSUE!! ON EXECUTION, THIS GIVES (NULL). THIS MEANS THE IMAGE HASNT BEEN GENERATED FOR SOME REASON CFUUIDRef newUniqueID= CFUUIDCreate(kCFAllocatorDefault); CFStringRef newUniqueIDString= CFUUIDCreateString(kCFAllocatorDefault, newUniqueID); / NSString *key= (__bridge NSString *)newUniqueIDString; item.imageKey=key; / NSLog(@"putting %@ in dictionary table",item.imageKey); [[BNRImageStore sharedStore] setImage:image forKey:item.imageKey]; / CFRelease(newUniqueIDString); CFRelease(newUniqueID); [imageView setImage:image]; NSLog(@"Dismissing Modal Controller"); [self dismissViewControllerAnimated:YES completion:NULL]; } @endWhen i tap the camera button on the DetailView to have the imagepicker pop up, i get my custom cameraview with the custom camera toolbar below it, presented as it should be. Upon tapping the camera button to capture an image, i experience a crash. Everytime. By this time, the shootPicture message has been passed and the control is inside the delegate method imagePickerController: didFinishPickingMediaWithInfo: Here are some of the last console messages corresponding to the crash. that were generated when i last ran the app via my iPad:-2017-12-11 21:19:47.719152+0530 HomePwner4[240:5980] Camera button tapped2017-12-11 21:19:47.724752+0530 HomePwner4[240:5980] init2017-12-11 21:19:47.725633+0530 HomePwner4[240:5980] Yes. The Camera is available. Start2017-12-11 21:19:47.729760+0530 HomePwner4[240:5980] current camera overlay- &lt;UIView: 0x100e8f720; frame = (0 0; 1024 768); layer = &lt;CALayer: 0x1c44336c0&gt;&gt;2017-12-11 21:19:47.730695+0530 HomePwner4[240:5980] Presenting Modal Controller- &lt;UIImagePickerController: 0x101839600&gt;2017-12-11 21:19:47.760145+0530 HomePwner4[240:5980] DetailsView disappearing2017-12-11 21:19:47.760550+0530 HomePwner4[240:5980] Removing image–– (null)2017-12-11 21:19:48.010549+0530 HomePwner4[240:5980] Drawing begun2017-12-11 21:19:48.010670+0530 HomePwner4[240:5980] Bounds: 1024.000000 708.0000002017-12-11 21:20:02.777216+0530 HomePwner4[240:5980] image selected from imagePicker- &lt;UIImagePickerController: 0x101839600&gt;2017-12-11 21:20:02.777361+0530 HomePwner4[240:5980] shot image- (null)2017-12-11 21:20:02.777502+0530 HomePwner4[240:5980] putting B453075A-13DB-4CB7-88C8-A3EB1298F805 in dictionary tablewarning: could not execute support code to read Objective-C class data in the process. This may reduce the quality of type information available.At first I was unable to dissect the problem. Then, i thought of determining whether the image is even being generated. So I NSLogged value of image pointer. As you can see above [Console Message: shot image- (null)], the value turns out to be null. Moreover, i haven't been able to fully understand the meaning or occurence of last console message (warning: could not execute .....).Any assistance to address this issue here would be greatly appreciated. Should you want me to present details on other objective-C objects like overlayView or any other, pls say so.Thank you.
Asked
by Rahul88.
Last updated .
Post marked as unsolved
3.6k Views

Deletion of account created during Xcode server setup

I am running Xcode 9 and i just created a server through it on my running admin account. This made the system create an "Other" account that shows up on the login screen and which i can log into using my admin credentials. It seems like its an alias to my admin account. I want to delete this account but i cannot see it listed under Users and Groups list in System Preferences. How do i go about doing so?
Asked
by Rahul88.
Last updated .
Post marked as solved
6.7k Views

Annotations not appearing on the mapView

1.) This is an issue related to MKAnnotation and partly data archiving using NSCoding.I am archiving some location pins which are first added into a singleton object named "mapPoints" of type NSArray (the rootobject), one object at a time. The "mapPoints" variable is an ivar of an object of class RooObject.When the app enters its background state, the AppDelegate object is made to pass the following method as a message:@implementation RootObject -(BOOL)saveChanges{ NSLog(@"%@", NSStringFromSelector(_cmd)); NSString *path= [self dataObjectArchivePath]; return [NSKeyedArchiver archiveRootObject:mapPoints toFile:path]; }And below is how I am unarchiving the saved data within the same implementation (RootObject):-(id)init{ if (self=[super init]) { NSString *path= [self dataObjectArchivePath]; mapPoints= [NSKeyedUnarchiver unarchiveObjectWithFile:path]; NSLog(@"%lu %p %@",sizeof(mapPoints),mapPoints, mapPoints); if (!mapPoints) { mapPoints= [[NSMutableArray alloc] init]; } } return self; }The pins show up on the mapView (known here as worldView) when I search for a location by inputting its name into the textfield of the app.Here is the code where, upon finding and updation of locations, the pins get added one pin at a time.@implementation WhereamiViewController -(void)findLocation{ NSLog(@"%@",NSStringFromSelector(_cmd)); [locationManager startUpdatingLocation];/ NSLog(@"location updated"); [activityIndicator startAnimating]; NSLog(@"hiding locationTitle field"); [locationTitleField setHidden:YES]; } -(BOOL)textFieldShouldReturn:(UITextField *)textField{ NSLog(@"%@",NSStringFromSelector(_cmd)); [self findLocation]; // findLocation message is sent. [textField resignFirstResponder]; NSLog(@"%@ resigns as first responder", textField); inputText= textField.text; NSLog(@"%@ %@", textField, textField.text); return YES; } /*Below is where I add a pin to the mapview*/ -(void)foundLocation:(CLLocation *)loc{ NSLog(@"%@",NSStringFromSelector(_cmd)); CLLocationCoordinate2D coord= [loc coordinate]; NSDateFormatter *formatter= [[NSDateFormatter alloc] init]; NSDate *currentDate= [[NSDate alloc] init]; [formatter setDefaultDate:currentDate]; BNRMapPoint *bmp= [[BNRMapPoint alloc] initWithCoordinate:coord title:inputText subTitle:[[formatter defaultDate] description]]; NSLog(@"%@", bmp); [rootObj.mapPoints addObject:bmp]; //This is where I add a newly created pin to the mapPoints (the singleton object which gets archived when app is in backgrd) [worldView addAnnotation:bmp]; MKCoordinateRegion region= MKCoordinateRegionMakeWithDistance(coord,250,250); [worldView setRegion:region animated:YES]; //RESET the UI [locationTitleField setText:@" "]; [activityIndicator stopAnimating]; [locationTitleField setHidden:NO]; [locationManager stopUpdatingLocation]; } -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ NSLog(@"%@", NSStringFromSelector(_cmd)); CLLocation *currentLocation= [locations lastObject]; NSTimeInterval t=[[currentLocation timestamp] timeIntervalSinceNow]; NSLog(@"current location–– %@",currentLocation); if (t&lt;-180) { NSLog(@"%@ location made more than 3 min ago.",currentLocation); return; / } [self foundLocation:currentLocation]; }Now, what want to have happen is to have the saved (archived) pins reappear when i rerun the app with its initial instance in memory expunged, so it runs from scratch but using the saved archived mapPoints "NSArray" object and all the data it contains.So I added a piece of code in my ViewController implementationHere is what my ViewController interface file looks like:@interface WhereamiViewController : UIViewController&lt;CLLocationManagerDelegate,MKMapViewDelegate,UITextFieldDelegate&gt; { @public RootObject *rootObj; CLLocationManager *locationManager; IBOutlet MKMapView *worldView; IBOutlet UIActivityIndicatorView *activityIndicator; IBOutlet UITextField *locationTitleField; } -(void)foundLocation:(CLLocation *)loc;This is to give you a better perspective by giving you an idea of the type of ivars delegate protocols i am to make use of, in the implementation file.And here is where i added the code for annotating the saved pins on my mapview (worldView). (This is only part of the implementation file) :@implementation WhereamiViewController -(void) viewDidLoad{ NSLog(@"%@",NSStringFromSelector(_cmd)); worldView.showsUserLocation=YES; NSLog(@"delegate- %@", worldView.delegate); } -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ NSLog(@"%@",NSStringFromSelector(_cmd)); CLLocationCoordinate2D centerCoordinate= [userLocation coordinate]; NSLog(@"%@ (%f, %f)",userLocation.location,centerCoordinate.latitude,centerCoordinate.longitude); MKCoordinateSpan span= MKCoordinateSpanMake(250, 250); MKCoordinateRegion mapPortionToDisplay= MKCoordinateRegionMakeWithDistance(centerCoordinate, span.latitudeDelta, span.longitudeDelta); if ([rootObj.mapPoints count]!=0){ //This is where i have tried to add the unarchived BNRMapPoint pins. But it hasn't shown any result NSLog(@"map-points not zero"); [worldView addAnnotations:rootObj.mapPoints]; } [worldView setRegion:mapPortionToDisplay animated:YES]; }The model object (BNRMapPoint object) class has been made to conform to NSCoding and MKAnnotation protocols@interface BNRMapPoint : NSObject&lt;MKAnnotation, NSCoding&gt; { double latitude; double longitude; @public NSArray *mapPoints; } -(id) initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t subTitle:(NSString *)st; @property (nonatomic, readonly) CLLocationCoordinate2D coordinate; @property (nonatomic, copy) NSString *title; @property (nonatomic,readonly,copy) NSString *subTitle; @end #import "BNRMapPoint.h" @implementation BNRMapPoint @synthesize coordinate; @synthesize title; @synthesize subtitle; -(void)encodeWithCoder:(NSCoder *)aCoder{ NSLog(@"%@",NSStringFromSelector(_cmd)); latitude = coordinate.latitude; longitude = coordinate.longitude; [aCoder encodeObject:self.title forKey:@"title"]; [aCoder encodeObject:_subTitle forKey:@"subTitle"]; [aCoder encodeDouble: latitude forKey:@"latitude"]; [aCoder encodeDouble:longitude forKey:@"longitude"]; } -(id)initWithCoder:(NSCoder *)aDecoder{ NSLog(@"%@",NSStringFromSelector(_cmd)); if (self= [super init]) { [self setTitle:[aDecoder decodeObjectForKey:@"title"]]; subtitle= [aDecoder decodeObjectForKey:@"subTitle"]; latitude= [aDecoder decodeDoubleForKey:@"latitude"]; longitude= [aDecoder decodeDoubleForKey:@"longitude"]; } return self; } -(id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t subTitle:(NSString *)st{ if (self= [super init]) { coordinate=c; title=t; subtitle=st; } return self; } -(id) init{ return [self initWithCoordinate:CLLocationCoordinate2DMake(43.07, -89.32) title:@"Hometown" subTitle:self.subtitle]; } -(NSString *)description{ return [NSString stringWithFormat:@"MapPoint titled %@ is located at &lt;%f,%f&gt;. Additional data–– %@",title,coordinate.latitude,coordinate.longitude,subtitle]; } @endI am not getting the archived location pins when i run the app the second time from scratch.Can anyone be kind enough to assist? Thank you. I am a CoreLocation and MapKit newbie.2.) And so, there is one more thing i wanted to know. The mapView first loads and has the setShowsUserLocation method send the delegate message- "-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation" to the viewcontroller (mapView's delegate), how does it internally make use of CoreLocation? In the console, i dont ever see "locationManager:didUpdateLocations" getting called after mapview's delegate receives the map based delegate message
Asked
by Rahul88.
Last updated .