I am loading a mapview with annotation. I have written the code as shown below. As I am new to OOPS I know that I may have committed a lot of mistakes. It would be really helpful, if someone would review my code and give some suggestions.
- (void)viewDidLoad
{
[super viewDidLoad];
if(groupOrContactSelected){
UIBarButtonItem *infoButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.infoButton];
UIBarButtonItem *segmentedButton = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
NSArray *toolbarItems = [NSArray arrayWithObjects: infoButtonItem, flexibleSpace, segmentedButton, nil];
[self setToolbarItems:toolbarItems];
self.navigationController.toolbar.translucent = true;
self.navigationController.toolbarHidden = NO;
[infoButtonItem release];
[segmentedButton release];
[flexibleSpace release];
mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
mapView.delegate=self;
[self.view addSubview:mapView];
addressbook = ABAddressBookCreate();
for (i = 0; i<[groupContentArray count]; i++) {
person = ABAddressBookGetPersonWithRecordID(addressbook,[[groupContentArray objectAtIndex:i] intValue]);
ABMultiValueRef addressProperty = ABRecordCopyValue(person, kABPersonAddressProperty);
NSArray *address = (NSArray *)ABMultiValueCopyArrayOfAllValues(addressProperty);
for (NSDictionary *addressDict in address)
{
addAnnotation = nil;
firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
NSString *country = [addressDict objectForKey:#"Country"];
NSString *streetName = [addressDict objectForKey:#"Street"];
NSString *cityName = [addressDict objectForKey:#"City"];
NSString *stateName = [addressDict objectForKey:#"State"];
NSString *fullAddress = [streetName stringByAppendingFormat:#"%#/%#/%#", cityName, stateName, country];
mapCenter = [self getLocationFromAddressString:fullAddress];
if(stateName != NULL || country != NULL || streetName != NULL || cityName != NULL){
addAnnotation = (SJAddressAnnotation *)[mapView dequeueReusableAnnotationViewWithIdentifier:[groupContentArray objectAtIndex:i]];
if(addAnnotation == nil){
addAnnotation = [[[SJAddressAnnotation alloc] initWithCoordinate:mapCenter title:firstName SubTitle:lastName Recordid:[groupContentArray objectAtIndex:i] ] autorelease];
[mapView addAnnotation:addAnnotation];}
}
}
CFRelease(addressProperty);
}
[self zoomToFitMapAnnotations:mapView];
[self.navigationItem setHidesBackButton:YES animated:YES];
NSString *mapTitle = localizedString(#"MAP_TITLE");
[self setTitle:mapTitle];
[segmentedControl addTarget:self action:#selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
NSString *close = localizedString(#"CLOSE");
UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:close style:UIBarButtonItemStylePlain target:self action:#selector(onClose:)];
self.navigationItem.rightBarButtonItem = closeButton;
self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
[closeButton release];
}
[searchDirectionSegmentedControl release];
[mapView release];
}
I may have committed a lot of mistakes. All suggestions will be appreciated. Thanks
Here is link which you can prefer and know how to structure the code properly http://www.highoncoding.com/Articles/804_Introduction_to_MapKit_Framework_for_iPhone_Development.aspx
Hope this help you.
Related
Hi I m creating a project where multiple Images Loading from Server With some like Count and Comment Count and a Button to like the image. I m showing the individual Images With using a Slider Controller like PageControl.
this is My code for Showing the View
-(UIView*)reloadView:(DPSliderView *)sliderView viewAtIndex:(NSUInteger)idx
{
_loading_view.hidden=TRUE;
if (idx < [photos count]) {
NSDictionary *item = [photos objectAtIndex:idx];
PhotoView *v = [[PhotoView alloc] init];
v.photoIndex = idx;
v.imageView.imageURL = [DPAPI urlForPhoto:item[#"photo_220x220"]];
NSString *placename1 = [item valueForKeyPath:#"spotting.item.name"];
NSString *firstCapChar1 = [[placename1 substringToIndex:1] capitalizedString];
NSString *cappedString1 = [placename1 stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar1];
v.spotNameLabel.text = cappedString1;
NSString *placename = [item valueForKeyPath:#"spotting.place.name"];
NSString *firstCapChar = [[placename substringToIndex:1] capitalizedString];
NSString *cappedString = [placename stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
NSString *place1=[NSString stringWithFormat:#"%#",cappedString];
NSString *address=[NSString stringWithFormat:#"%#",[item valueForKeyPath:#"spotting.place.address"]];
NSString *location_str3 = [NSString stringWithFormat:#"# %#, %#",place1,address];
int cap_len=[place1 length];
int address_lenth=[address length];
ZMutableAttributedString *str = [[ZMutableAttributedString alloc] initWithString:location_str3
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
[[FontManager sharedManager] zFontWithName:#"Lucida Grande" pointSize:12],
ZFontAttributeName,
nil]];
[str addAttribute:ZFontAttributeName value:[[FontManager sharedManager] zFontWithName:#"Lucida Grande" pointSize:12] range:NSMakeRange(0, cap_len+3)];
[str addAttribute:ZForegroundColorAttributeName value:[UIColor colorWithRed:241/255.0f green:73.0/255.0f blue:2.0/255.0f alpha:1.0]range:NSMakeRange(0, cap_len+3)];
[str addAttribute:ZForegroundColorAttributeName value:[UIColor colorWithRed:128.0/255.0f green:121.0/255.0f blue:98.0/255.0f alpha:1.0]range:NSMakeRange(cap_len+4, address_lenth)];
v.placefontlabel.zAttributedText=str;
v.likesCountLabel.text = [NSString stringWithFormat:#"%i", [item[#"likes_count"] intValue]];
if ([_device_lang_str isEqualToString:#"es"])
{
v.shightingsLabel.text = [NSString stringWithFormat:NSLocalizedString(#"%i Vistas", nil), [item[#"sightings_count"] intValue]];
}
else
{
v.shightingsLabel.text = [NSString stringWithFormat:NSLocalizedString(#"%i Sightings", nil), [item[#"sightings_count"] intValue]];
}
if ([nolocationstr isEqualToString:#"YES"])
{
v.distanceLabel.text =[NSString stringWithFormat:#"%.2f km", [item[#"distance"] floatValue]];
}
else
{
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:[[item valueForKeyPath:#"spotting.place.lat"]floatValue] longitude:[[item valueForKeyPath:#"spotting.place.lng"] floatValue]];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:[_explore_lat_str floatValue] longitude:[_explore_lng_str floatValue]];
NSString *lat_laong=[NSString stringWithFormat:#"%f",[location1 distanceFromLocation:location2]];
int km=[lat_laong floatValue]*0.001;
NSString *distancestr=[NSString stringWithFormat:#"%d km",km];
float dist=[distancestr floatValue];
v.distanceLabel.text = [NSString stringWithFormat:#"%.2f km", dist];
}
if (![item[#"likes"] boolValue]) {
v.likeButton.enabled = YES;
v.likeButton.tag = idx;
[v.likeButton setImage:[UIImage imageNamed:#"like_new.png"] forState:UIControlStateNormal];
[v.likeButton addTarget:self action:#selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
}
else
{
v.likeButton.tag = idx;
[v.likeButton setImage:[UIImage imageNamed:#"like_new1.png"] forState:UIControlStateNormal];
}
NSArray *guides = item[#"guides"];
if ([guides count] > 0) {
NSString *guideType = [[guides objectAtIndex:0] valueForKey:#"type"];
UIImage *guidesIcon = [UIImage imageNamed:[NSString stringWithFormat:#"%#.png", guideType]];
v.guideButton.hidden = NO;
v.guideButton.tag = idx;
[v.guideButton setImage:guidesIcon forState:UIControlStateNormal];
[v.guideButton addTarget:self action:#selector(guideAction:) forControlEvents:UIControlEventTouchUpInside];
}
v.shareButton.tag = idx;
[v.shareButton addTarget:self action:#selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(photoTapGesture:)];
[v addGestureRecognizer:tapGesture];
[tapGesture release];
return [v autorelease];
} else {
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"sc_img.png"]];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.center = CGPointMake(CGRectGetMidX(iv.bounds), 110);
[indicator startAnimating];
[iv addSubview:indicator];
[indicator release];
return [iv autorelease];
}
}
Now My question is :
If i will Click on Like Button , Then i have to change the button image as well as like count. I can able to Change the Button Image By This Method
[sender setImage:[UIImage ImageNamed:#"image.png"]];
But How can I change the Like count of the Label ? How can i access the Particular label of the View ? I have assigned the tag But , I dont know how to assign it.I dont want to Reload Whole Slider as the Photo are loading from Network (Remote Server) . Thanks for your Time.
Just keep a reference to the label and update that.
// #interface
#property (nonatomic, strong) UILabel *myLabel;
// #implementation
_myLabel.text = #"Whatever.";
If you have multiple labels, set the tags when you create your views
newView.tag = sequenceNumber +100;
And then update
-(void)updateLabelWithTag:(NSInteger)tag {
UILabel *label = (UILabel*) [self.scrollView viewWithTag:tag];
label.text = #"Whatever.";
}
In my implementation of TTLauncherView, only loads the first page. Why?
I have 47 items in array, 47 items div 9 items by page, I should have 6 pages.
Thanks for helping.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSMutableString *jsonString = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
NSArray *photos = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
launcherView = [[TTLauncherView alloc] initWithFrame:self.view.bounds];
launcherView.backgroundColor = [UIColor whiteColor];
launcherView.delegate = self;
launcherView.columnCount = 3;
launcherView.persistenceMode = TTLauncherPersistenceModeNone;
NSMutableArray *itemArray = [[NSMutableArray alloc] init];
for (NSDictionary *photo in photos)
{
NSString *iconURLString = [NSString stringWithFormat:#"http://farm%#.static.flickr.com/%#/%#_%#_s.jpg",
[photo objectForKey:#"farm"], [photo objectForKey:#"server"], [photo objectForKey:#"primary"], [photo objectForKey:#"secret"]];
NSDictionary *title = [photo objectForKey:#"title"];
NSString *itemTitle = [title objectForKey:#"_content"];
TTLauncherItem *itemMenu = [[[TTLauncherItem alloc] initWithTitle:itemTitle
image:iconURLString
URL:nil
canDelete:NO] autorelease];
[itemArray addObject:itemMenu];
}
launcherView.pages = [NSArray arrayWithObject: itemArray];
[self.view addSubview:launcherView];
}
As I recall, TTLauncherView doesn't break up the TTLauncherItem's into pages automatically. You need an array of arrays. All of the launcher item's in the first array will be on the first page, all the launcher item's in the second array will be on the second page etc. It has been a long time since I've used it, but I think that's how it worked.
My modified code with the hint of #Darren
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSMutableString *jsonString = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue];
NSArray *photos = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
NSMutableArray *itemArray = [[NSMutableArray alloc] init];
NSMutableArray *pageArray = [[NSMutableArray alloc] init];
NSNumber *countPage = [[NSNumber alloc] initWithInt:0];
for (NSDictionary *photo in photos)
{
NSString *iconURLString = [NSString stringWithFormat:#"http://farm%#.static.flickr.com/%#/%#_%#_s.jpg",
[photo objectForKey:#"farm"], [photo objectForKey:#"server"], [photo objectForKey:#"primary"], [photo objectForKey:#"secret"]];
NSString *photoCount = [photo objectForKey:#"photos"];
NSDictionary *title = [photo objectForKey:#"title"];
NSString *itemTitle = [title objectForKey:#"_content"];
TTLauncherItem *itemMenu = [[[TTLauncherItem alloc] initWithTitle:itemTitle
image:iconURLString
URL:nil
canDelete:NO] autorelease];
itemMenu.badgeValue = photoCount;
[itemArray addObject:itemMenu];
int value = [countPage intValue];
countPage = [NSNumber numberWithInt:value + 1];
if (countPage == [NSNumber numberWithInt:9]){
countPage = [NSNumber numberWithInt:0];
[pageArray addObject:itemArray];
itemArray = [[NSMutableArray alloc] init];
}
}
[pageArray addObject:itemArray];
launcherView = [[TTLauncherView alloc] initWithFrame:self.view.bounds];
launcherView.backgroundColor = [UIColor blackColor];
launcherView.delegate = self;
launcherView.columnCount = 3;
launcherView.persistenceMode = TTLauncherPersistenceModeNone;
launcherView.pages = pageArray;
[self.view addSubview:launcherView];
}
I have a button that saves cell's data upon ButtonClick
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.checkbox = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect checkboxRect = CGRectMake(135, 150, 36, 36);
[self.checkbox setFrame:checkboxRect];
[self.checkbox setImage:[UIImage imageNamed:#"unselected#2x.png"]forState:UIControlStateNormal];
[self.checkbox setImage:[UIImage imageNamed:#"selected#2x.png"] forState:UIControlStateSelected];
[self.checkbox addTarget:self action:#selector(checkboxClicked:) forControlEvents:UIControlEventTouchUpInside];
self.accessoryView = self.checkbox;
array = [NSMutableArray array];
}
return self;
}
-(void)checkboxClicked:(UIButton *)sender{
sender.selected = !sender.selected;
UITableViewCell *cell = (AddressBookCell *)sender.superview;
if(sender.selected){
[array addObject:cell];
}
}
and i use that array in my other class, but it keeps giving me empty arrays;
this is my other class, it gives me a log of Zero.
-(void)textMessage{
/*UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Not Implmeneted Yet" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
[alert release];*/
AddressBookCell *names = [[AddressBookCell alloc]init];
NSLog(#"%d",[[names array]count]);
}
![1] http://min.us/m2GMsoRap
I need a way to store data upon button click and transfer it to my other classes.
EDIT## full code
#import "AddressBookCell.h"
#implementation AddressBookCell
#synthesize checkbox;
#synthesize array;
#synthesize addressController;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.checkbox = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect checkboxRect = CGRectMake(135, 150, 36, 36);
[self.checkbox setFrame:checkboxRect];
[self.checkbox setImage:[UIImage imageNamed:#"unselected#2x.png"]forState:UIControlStateNormal];
[self.checkbox setImage:[UIImage imageNamed:#"selected#2x.png"] forState:UIControlStateSelected];
[self.checkbox addTarget:self action:#selector(checkboxClicked:) forControlEvents:UIControlEventTouchUpInside];
self.accessoryView = self.checkbox;
array = [[NSMutableArray alloc]init];
}
return self;
}
-(void)checkboxClicked:(UIButton *)sender{
sender.selected = !sender.selected;
UITableViewCell *cell = (AddressBookCell *)sender.superview;
NSLog(#"%d'",cell.tag);
if(sender.selected){
[array addObject:cell];
}else{
if([array containsObject:cell]){
[array removeObject:cell];
}
NSLog(#"%d", [array count]);
}
}
and now my other class
-(void)setUpContacts{
NSDictionary *alphabet = [[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:0],#"A",[NSNumber numberWithInt:1],#"B",[NSNumber numberWithInt:2],#"C",[NSNumber numberWithInt:3],#"D",[NSNumber numberWithInt:4],#"E",[NSNumber numberWithInt:5],#"F",[NSNumber numberWithInt:6],#"G",[NSNumber numberWithInt:7],#"H",[NSNumber numberWithInt:8],#"I",[NSNumber numberWithInt:9],#"J",[NSNumber numberWithInt:10],#"K",[NSNumber numberWithInt:11],#"L",[NSNumber numberWithInt:12],#"M",[NSNumber numberWithInt:13],#"N",[NSNumber numberWithInt:14],#"O",[NSNumber numberWithInt:15],#"P",[NSNumber numberWithInt:16],#"Q",[NSNumber numberWithInt:17],#"R",[NSNumber numberWithInt:18],#"S",[NSNumber numberWithInt:19],#"T",[NSNumber numberWithInt:20],#"U",[NSNumber numberWithInt:21],#"V",[NSNumber numberWithInt:22],#"W",[NSNumber numberWithInt:23],#"X",[NSNumber numberWithInt:24],#"Y",[NSNumber numberWithInt:25],#"Z", nil];
NSMutableArray *tempArray = [[NSMutableArray alloc]init];
for(int i = 0; i<=27; i++){
[tempArray addObject:[NSNull null]];
}
Contacts *contact = [[Contacts alloc]init];
contactNumbers = [contact phoneNumbers];
for (NSDictionary* info in contactNumbers) {
firstLetter = [info objectForKey:#"lastName"];
int index = 27;
if([firstLetter length] > 0){
firstLetter =[NSString stringWithFormat:#"%C",[firstLetter characterAtIndex:0]];
firstLetter= [firstLetter capitalizedString];
if([alphabet objectForKey:firstLetter]){
NSNumber *t = [alphabet valueForKey:firstLetter];
index = [t intValue] + 1;
}
}
if([tempArray objectAtIndex:index] == [NSNull null]){
[tempArray insertObject:[NSMutableArray array] atIndex:index];
}
[[tempArray objectAtIndex:index] addObject:info];
}
[alphabet release];
NSArray *alphabet2 = [[NSArray alloc]initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
NSMutableArray *tempArray2 = [[NSMutableArray alloc]init];
NSMutableArray *titleTemp = [[NSMutableArray alloc]init];
int c = 0;
for(int i = 0; i<=27; i++){
if([tempArray objectAtIndex:i] != [NSNull null]){
if(i == 0){
[titleTemp insertObject:#"Suggested" atIndex:c];
}else if(i == 27){
[titleTemp insertObject:#"Others" atIndex:c];
}else{
int loc = i -1;
[titleTemp insertObject:[alphabet2 objectAtIndex:loc] atIndex:c];
}
[tempArray2 insertObject:[tempArray objectAtIndex:i] atIndex:c];
c++;
}
}
[alphabet2 release];
[tempArray release];
letterArray = tempArray2;
titlePointer = titleTemp;
}
-(void)textMessage{
/*UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Not Implmeneted Yet" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
[alert release];*/
AddressBookCell *names = [[AddressBookCell alloc]init];
savedArray = [NSArray arrayWithArray:[names array]];
NSLog(#"%#",savedArray);
}
- (void)viewDidLoad{
[super viewDidLoad];
[self setUpContacts];
indexPaths = [[NSMutableDictionary alloc]init];
//suggestedPeople = [[NSArray alloc]initWithObjects:#"User1",#"User2",#"User3",#"User4", nil];
//set up the tableView
self.myTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
self.title = #"Select Friends";
self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:myTableView];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:#"Text"style:UIBarButtonItemStylePlain target:self action:#selector(textMessage)];
//testing section
}
Of course it's empty, you alloc/init'd a new instance of AdressBookCell in your other class, so it doesn't have anything in its array. You need a property in your other class that points to the instance of your first class where you fill your array, and then you can use [pointerToFirstClass array] to get at that array.
It looks like you are using manual memory management. If not, you need to specify.
In the case that you are, when you create the array with the line [NSMutableArray array], you are creating an autoreleased object that will be released before your other class tries to access it.
You'll need to retain it at the point you create it, and release it in your dealloc. If you change [NSMutableArray array] to [[NSMutableArray array] retain] and add an [array release] line to your dealloc the array won't disappear on you until you release the owning object.
you haven't included enough info to tell what is going on, but I can guess...
a log of zero could mean an empty array, or more likely a nil array... try this:
AddressBookCell *names = [[AddressBookCell alloc]init];
NSLog(#"%#",[names array]);
I am loading a MKMapView with some pins, which drops based on address co-ordinates. Everything is working fine until, I keep the mapview open for sometime(2 minutes). And then it crashes, without an event actually taking place. What could be the reason for this.
In my viewDidLoad I write the following code
mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
mapView.delegate=self;
[self.view addSubview:mapView];
addressbook = ABAddressBookCreate();
for (i = 0; i<[groupContentArray count]; i++) {
NSLog(#"group content array %#", groupContentArray);
person = ABAddressBookGetPersonWithRecordID(addressbook,[[groupContentArray objectAtIndex:i] intValue]);
NSLog(#"Person %#", person);
ABMultiValueRef addressProperty = ABRecordCopyValue(person, kABPersonAddressProperty);
NSArray *address = (NSArray *)ABMultiValueCopyArrayOfAllValues(addressProperty);
NSLog(#"Address %#", address);
for (NSDictionary *addressDict in address)
{
addAnnotation = nil;
firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
NSString *country = [addressDict objectForKey:#"Country"];
NSString *streetName = [addressDict objectForKey:#"Street"];
NSString *cityName = [addressDict objectForKey:#"City"];
NSString *stateName = [addressDict objectForKey:#"State"];
if (streetName == (id)[NSNull null] || streetName.length == 0 ) streetName = #"";
if (stateName == (id)[NSNull null] || stateName.length == 0 ) stateName = #"";
if (cityName == (id)[NSNull null] || cityName.length == 0 ) cityName = #"";
if (country == (id)[NSNull null] || country.length == 0 ) country = #"";
NSString *fullAddress = [streetName stringByAppendingFormat:#"/%#/%#/%#", cityName, stateName, country];
mapCenter = [self getLocationFromAddressString:fullAddress];
if(stateName != NULL || country != NULL || streetName != NULL || cityName != NULL){
if ((mapCenter.latitude == 0) && (mapCenter.longitude == 0))
{
//Alert View
}
else{
if(addAnnotation == nil){
addAnnotation = [[[MyAddressAnnotation alloc] initWithCoordinate:mapCenter title:firstName SubTitle:lastName Recordid:[groupContentArray objectAtIndex:i] ]autorelease];
[mapView addAnnotation:addAnnotation];}
else{
// ALert View
}
}
}
}
CFRelease(addressProperty);
}
[self zoomToFitMapAnnotations:mapView];
[self.navigationItem setHidesBackButton:YES animated:YES];
NSString *mapTitle = localizedString(#"MAP_TITLE");
[self setTitle:mapTitle];
[segmentedControl addTarget:self action:#selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
Try this:
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *topBar = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"header1.png"]];
topBar.frame = CGRectMake(0, 0, 320, 44);
[self.navigationController.navigationBar insertSubview:topBar atIndex:0];
[topBar release];
self.navigationController.navigationBarHidden=YES;
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
[mapView setShowsUserLocation:YES];
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = [strLat doubleValue];
region.center.longitude = [strLong doubleValue];
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
mapAnonotationView *ann = [[mapAnonotationView alloc] init];
ann.title = name;
ann.subtitle = Address;
ann.coordinate = region.center;
[mapView addAnnotation:ann];
[ann release];
ann = nil;
}
Setting the mapview delegate to nil in the dealloc method solved my problem.
I was having crashes with my iPhone4S and console revealed nan values for region. After trying about 7 different solutions from SO and various suggestions from Apple DTS, I solved it by eliminating the regionThatFits call. I simply used:
CLLocationDistance visibleDistance = 100000; // 100 kilometers
MKCoordinateRegion adjustedRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, visibleDistance, visibleDistance);
[_mapView setRegion:adjustedRegion animated:YES];
Apparently there is a problem with that regionThatFits method.
Hey guys, I have the strangest bug in my application I'm developing.
The thing is I have a login screen with two textfields that I create, add as subviews and release, all done in viewDidLoad.
Then as the user has logged in and logs out again, the textfields appear as normal but when the login-method is called it thinks the textfields are empty!
I have also only found this bug on iOS 4.2.1 (8C148a)
Furthemore the log show "Received memory warning. Level=1" and sometimes "Level=2" and this might be related but I don't know.
Can anyone help me? I'm quite lost...
My viewDidLoad:
userNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 85, 280, 30)];
userNameTextField.returnKeyType = UIReturnKeyNext;
userNameTextField.placeholder = #"Användarnamn:";
userNameTextField.layer.cornerRadius = 8;
userNameTextField.alpha = 0.9;
userNameTextField.opaque = YES;
userNameTextField.tag = 0;
userNameTextField.backgroundColor = [UIColor whiteColor];
userNameTextField.textAlignment = UITextAlignmentCenter;
userNameTextField.textAlignment = UIBaselineAdjustmentAlignBaselines;
userNameTextField.borderStyle = UITextBorderStyleRoundedRect;
userNameTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
userNameTextField.adjustsFontSizeToFitWidth = FALSE;
[userNameTextField addTarget:self
action:#selector(textFieldDidReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 119, 280, 30)];
passwordTextField.returnKeyType = UIReturnKeyDone;
passwordTextField.placeholder = #"Lösenord:";
passwordTextField.secureTextEntry = YES;
passwordTextField.layer.cornerRadius = 8;
passwordTextField.alpha = 0.9;
passwordTextField.opaque = NO;
passwordTextField.tag = 1;
passwordTextField.backgroundColor = [UIColor whiteColor];
passwordTextField.textAlignment = UITextAlignmentCenter;
passwordTextField.textAlignment = UIBaselineAdjustmentAlignBaselines;
passwordTextField.borderStyle = UITextBorderStyleRoundedRect;
passwordTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
passwordTextField.adjustsFontSizeToFitWidth = TRUE;
[passwordTextField addTarget:self
action:#selector(textFieldDidReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
[self.view addSubview:userNameTextField];
[self.view addSubview:passwordTextField];
userNameTextField.delegate = self;
passwordTextField.delegate = self;
[userNameTextField release];
[passwordTextField release];
I also use the following methods:
-(void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *)event {
[userNameTextField resignFirstResponder];
[passwordTextField resignFirstResponder];
[super touchesBegan:touches withEvent:event ];}
-(IBAction)textFieldDone:(id)sender {
[sender resignFirstResponder];}
-(BOOL)textFieldDidReturn:(UITextField *)textfield {
NSInteger nextTextFieldTag = textfield.tag + 1;
// Find next responding textfield
UIResponder *nextRespondingTextField = [textfield.superview viewWithTag:nextTextFieldTag];
if (nextRespondingTextField) {
[nextRespondingTextField becomeFirstResponder];
} else {
[self logInUser];
[textfield resignFirstResponder];
}
return NO;}
-(IBAction) logInUser {
// Popup alert
if (userNameTextField.text.length == 0 && passwordTextField.text.length == 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Vänligen ange användarnamn och lösenord." delegate:nil cancelButtonTitle:#"Stäng." otherButtonTitles:nil];
[alert show];
[alert release];
} else if (passwordTextField.text.length == 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Vänligen ange lösenord." delegate:nil cancelButtonTitle:#"Stäng." otherButtonTitles:nil];
[alert show];
[alert release];
} else if (userNameTextField.text.length == 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Vänligen ange användarnamn." delegate:nil cancelButtonTitle:#"Stäng." otherButtonTitles:nil];
[alert show];
[alert release];
} else {
PreschoolAppDelegate *globalAppDelegate = [[UIApplication sharedApplication] delegate];
// Set global username and password
globalAppDelegate.globalUserName = #"";
globalAppDelegate.globalPassword = #"";
globalAppDelegate.globalUserName = userNameTextField.text;
globalAppDelegate.globalPassword = passwordTextField.text;
// Clear variables
globalAppDelegate.globalFirstname = [[NSMutableString alloc] init];
globalAppDelegate.globalLastname = [[NSMutableString alloc] init];
globalAppDelegate.globalChildFirstname = [[NSMutableString alloc] init];
globalAppDelegate.globalChildSurname = [[NSMutableString alloc] init];
globalAppDelegate.globalChildFullname = [[NSMutableString alloc] init];
globalAppDelegate.globalSelectedChild = [[NSMutableString alloc] init];
globalAppDelegate.globalIdString = [[NSMutableString alloc] init];
globalAppDelegate.globalChildIdString = [[NSMutableString alloc] init];
globalAppDelegate.globalSelectedChildId = [[NSString alloc] init];
globalAppDelegate.globalWipChildList = [[NSMutableArray alloc] init];
globalAppDelegate.globalChildIdList = [[NSMutableArray alloc] init];
globalAppDelegate.globalChildList = [[NSMutableArray alloc] init];
globalAppDelegate.globalWipChildArray = [[NSMutableArray alloc] init];
globalAppDelegate.tempGlobalAbsenceArray = [[NSMutableArray alloc] init];
globalAppDelegate.tempGlobalChildArray = [[NSMutableArray alloc] init];
globalAppDelegate.globalAbsenceDescription = [[NSMutableArray alloc] init];
globalAppDelegate.globalVacationDescription = [[NSMutableArray alloc] init];
globalAppDelegate.tempGlobalVacationArray = [[NSMutableArray alloc] init];
globalAppDelegate.globalVacationWipChildArray = [[NSMutableArray alloc] init];
globalAppDelegate.globalVacationStartDate = [[NSMutableArray alloc] init];
globalAppDelegate.globalVacationEndDate = [[NSMutableArray alloc] init];
globalAppDelegate.globalVacationStartDates = [[NSMutableArray alloc] init];
globalAppDelegate.globalVacationEndDates = [[NSMutableArray alloc] init];
//
// Start the fetch of the data from the rest service
//
userClient = [[GetUserListRestClient alloc] init];
[userClient getUsers:self];
[pendingLogin startAnimating];
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector (checkIfConnFinished:) userInfo:nil repeats:YES];
}}
I think the problems are in the property assignments like this:
globalAppDelegate.globalFirstname = [[NSMutableString alloc] init];
globalAppDelegate.globalWipChildList = [[NSMutableArray alloc] init];
This way your Strings and Arrays you created are never released. This caused the memory warnings. The good way is this:
NSMutableString *str = [[NSMutableString alloc] init];
globalAppDelegate.globalFirstname = str;
[str release];
Or a shorter but not as good solution:
globalAppDelegate.globalWipChildList = [[[NSMutableArray alloc] init] autorelease];
I hope I could help.