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.
Related
I am new to IOS development. I am developing an app which requires a form to be filled by the user for the user details. The details includes a Date of Birth Field for which I am using UIDatePicker. I am adding those UIDatePicker and UIActionSheet programatically and wanted to update the date on a label. The dates are getting updated however they are getting overwritten on same label.
Here is the code
-(IBAction)dateButtonClicked:(id)sender {
actionSheet = [[UIActionSheet alloc] initWithTitle:#"Choose Date"delegate:self cancelButtonTitle:#"cancel" destructiveButtonTitle:nil otherButtonTitles:#"Select",nil];
[actionSheet showInView:self.view ];
[actionSheet setFrame:CGRectMake(0, 117, 320, 383)];
}
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet {
datePickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 320, 216)];
[datePickerView setMinuteInterval:5];
[datePickerView setTag: kDatePickerTag];
[actionSheet addSubview:datePickerView];
datelabel = [[UILabel alloc] init];
datelabel.frame = CGRectMake(55, 92, 300, 50);
datelabel.backgroundColor = [UIColor clearColor];
datelabel.textColor = [UIColor blackColor];
datelabel.font = [UIFont fontWithName:#"Verdana-Bold" size: 12.0];
datelabel.textAlignment = UITextAlignmentCenter;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: #"MM/dd/YYYY h:mm a"];
datelabel.text = [NSString stringWithFormat:#"%#",
[formatter stringFromDate:[NSDate date]]];
[self.view addSubview:datelabel];
NSArray *subviews = [actionSheet subviews];
[[subviews objectAtIndex:SelectButtonIndex] setFrame:CGRectMake(20, 266, 280, 46)];
[[subviews objectAtIndex:CancelButtonIndex] setFrame:CGRectMake(20, 317, 280, 46)];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex != [actionSheet cancelButtonIndex]) {
[datePickerView addTarget:self
action:#selector(LabelChange:)
forControlEvents:UIControlEventValueChanged];
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Date" message:msg delegate:nil cancelButtonTitle: #"Dismiss" otherButtonTitles:nil];
// [alert show];
}
}
- (void)LabelChange:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
datelabel.text = [NSString stringWithFormat:#""];
datelabel.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:datePickerView.date]];
}
Please let me know the changes needs to be done in order to void such problem.
This code works for me like a charm !!!
in .h file
#import <UIKit/UIKit.h>
#interface EXPViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate, UIActionSheetDelegate>{
UIActionSheet *pickerViewPopup;
UIDatePicker *pickerView;
IBOutlet UILabel *dateLabel;
}
- (IBAction)dateButtonClicked:(id)sender;
#end
In .m file:
-(IBAction)dateButtonClicked:(id)sender{
[self showPickerView];
}
-(void)showPickerView {
pickerViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
pickerView = nil;
pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];
((UIDatePicker*)pickerView).datePickerMode = UIDatePickerModeDate;
((UIDatePicker*)pickerView).date = [NSDate date];
UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(cancelButtonPressed:)];
[barItems addObject:cancelBtn];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneButtonPressed:)];
[barItems addObject:doneBtn];
[pickerToolbar setItems:barItems animated:YES];
[barItems release];
[pickerViewPopup addSubview:pickerToolbar];
[pickerViewPopup addSubview:pickerView];
[pickerViewPopup showInView:self.view];
[pickerViewPopup setBounds:CGRectMake(0, 0, 320, 464)];
}
-(void)doneButtonPressed:(id)sender {
//Do something here here with the value selected using [pickerView date] to get that value
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd, MMM YYYY"];
NSString* dateString = [dateFormat stringFromDate:((UIDatePicker*)pickerView).date];
yourLabel.text = dateString;
[pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
}
-(void)cancelButtonPressed:(id)sender{
[pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
}
This is because whenever your dateButtonClicked action is fire , datePickerView and datelabel allocating again and again, so just do one thing, put your code of datePickerView and datelabel code outside dateButtonClicked clicked , you can put in viewDIdLoad
You can implement delegate method of picker,
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
}
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]);
My array contain (firstName,lastName, age) at each index. now I want to change age of a person at index 1. please guide how to do it. Here is my code.
- (void)viewDidLoad {
[super viewDidLoad];
productArray=[[NSMutableArray alloc]init];
PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = #"Adeem";
personObj.lastName = #"Basraa";
personObj.age = #"5";
[productArray addObject:personObj];
[personObj release];
PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = #"Ijaz";
personObj.lastName = #"Ahmed";
personObj.age = #"10";
[productArray addObject:personObj];
[personObj release];
PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = #"Waqas";
personObj.lastName = #"Ahmad";
personObj.age = #"15";
[productArray addObject:personObj];
[personObj release];
}
Person *person = (Person *)[myArray objectAtIndex:1];
person.age = 2;
Assuming Person is your custom object stored in the array
use this
[arrname replaceObjectAtIndex:1 withObject:[NSNumber numberWithInt:13]];//13 is the age you want to change
You should use NSMutableDictionary to save name,age,phone,address and add this dictionary to your array.
[[arry objectAtIndex:1] setObject:#"value" forKey:#"key"];
Like this you can change value.
try this
-insertObject:atIndex: or replaceObjectAtIndex:withObject:
Perhaps this will help you.
- (void)viewDidLoad {
[super viewDidLoad];
productArray=[[NSMutableArray alloc]init];
PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = #"Adeem";
personObj.lastName = #"Basraa";
personObj.phoneNumber = #"123456789";
[productArray addObject:personObj];
[personObj release];
PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = #"Ijaz";
personObj.lastName = #"Ahmed";
personObj.phoneNumber = #"987654321";
[productArray addObject:personObj];
[personObj release];
PersonDetail *personObj = [[PersonDetail alloc] init];
personObj.firstName = #"Waqas";
personObj.lastName = #"Ahmad";
personObj.phoneNumber = #"45656789";
[productArray addObject:personObj];
[personObj release];
}
- (void)change {
for (int i=0;i<[productArray count];i++) {
PersonDetail *personObj = (PersonDetail *)[[productArray objectAtIndex:i] retain];
personObj.phoneNumber = #"New";
}
}
Supposing your NSMutableArray consists of NSMutableDictionary objects,
try something like this :
NSMutableDictionary* entry = [entries objectAtIndex:index];
[entry setValue:#"newAge" forKey:#"Age"];
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.
i am beginner in iphone programming i am doing an app of photo gallery in which while scrolling the UITableView i am getting this exception in my device as Program received signal: “EXC_BAD_ACCESS”
can anyone pls help me tackle this problem...
enter cod[super viewDidLoad];
self.title=#"Back";
udf=[NSUserDefaults standardUserDefaults];
id_arr=[[NSMutableArray alloc]init];
descrip_arr=[[NSMutableArray alloc]init];
path_arr=[[NSMutableArray alloc]init];
count_arr=[[NSMutableArray alloc]init];
client = [[[ClientController alloc] init] autorelease];
r_m = [[[RequestMessage alloc]init] autorelease];
m_j = [[[Main_Json alloc]init] autorelease];
[r_m setServiceType:#"IMAGE"];
[r_m setParameter:#"sample string"];
NSString * json_string = [m_j returnJsonString:r_m:#"button"];
json_string=[json_string stringByAppendingFormat: #"\n"];
NSLog(#"Client is sending:%#", json_string);
//NSLog(json_string);
client.connect;
NSLog(#"client connecting........");
if([client isConnected])
{
NSString *flag = [client send:json_string];
if(![flag isEqualToString:#"success"])
{
NSLog(#"Before Alert_view");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:flag delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
NSString *Var=[client receiveResponse];
//NSLog(#"TEST:%#",Var);
NSString *main_str=[Var stringByReplacingOccurrencesOfString:#"!#{}&" withString:#""];
//main_str=[Var stringByReplacingOccurrencesOfString:#"{\"serviceType\":\"ALLIMAGE\",\"parameters\":[[]]}" withString:#""];
NSLog(#"Split:%#",main_str);
js=[[JsontoObject alloc]sivajiTV_response:main_str];
e1=[[Event alloc]init];
NSLog(#"TEST1:%#",[udf objectForKey:#"id_value"]);
NSLog(#"TEST2:%#",[udf objectForKey:#"des_value"]);
NSLog(#"TEST3:%#",[udf objectForKey:#"path_value"]);
NSLog(#"TEST4:%#",[udf objectForKey:#"count_value"]);
id_arr=[[udf objectForKey:#"id_value"] componentsSeparatedByString:#","];
NSArray *descrip_arr1 =[[udf objectForKey:#"des_value"] componentsSeparatedByString:#","];
NSArray *path_arr1=[[udf objectForKey:#"path_value"] componentsSeparatedByString:#","];
count_arr=[[udf objectForKey:#"count_value"] componentsSeparatedByString:#","];
//NSLog(#"-------------");
//NSLog(#"STRING_ID2:%#",descrip_arr1);
//NSLog(#"STRING_ID3:%#",path_arr1);
//NSLog(#"-------------");
for (int i=0; i<[descrip_arr1 count]; i++) {
NSString *temp=[NSString stringWithFormat:#"%#",[descrip_arr1 objectAtIndex:i]];
//NSLog(#"STRING_test:%#",temp);
temp=[temp stringByReplacingOccurrencesOfString:#"\"" withString:#""];
//NSLog(#"STRING_test1:%#",temp);
[descrip_arr addObject:temp];
NSString *temp1=[NSString stringWithFormat:#"%#",[path_arr1 objectAtIndex:i]];
temp1=[temp1 stringByReplacingOccurrencesOfString:#"\"" withString:#""];
[path_arr addObject:temp1];
}
NSLog(#"------------------------------------------------------------------------------");
NSLog(#"STRING_ID1:%#",id_arr);
NSLog(#"STRING_ID2:%#",descrip_arr);
NSLog(#"STRING_ID3:%#",path_arr);
NSLog(#"STRING_ID4:%#",count_arr);
NSLog(#"------------------------------------------------------------------------------");
if([main_str isEqualToString: [NSNull null]])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:main_str delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
}
else
{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:nil message:#"Connection not Found" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert1 show];
[alert1 release];
}
UILabel *lblTitle=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 40)];
lblTitle.backgroundColor=[UIColor clearColor];
self.navigationItem.titleView=lblTitle;
toolbar=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 25)];
toolbar.barStyle=UIBarStyleBlackOpaque;
[self.view addSubview:toolbar];
UILabel *mylabel = [[UILabel alloc] initWithFrame:CGRectMake(250, 2, 60, 20)];
mylabel.backgroundColor=[UIColor clearColor];
mylabel.textColor = [UIColor whiteColor];
mylabel.text = #"Gallery";
[toolbar addSubview:mylabel];
myTableView.frame=CGRectMake(0,26, 320,430);
// myTableView.backgroundView=nil;
[self.view addSubview:myTableView];
//self.myTableView.separatorColor = [UIColor clearColor];
//UITableViewController *myTableViewController = [[UITableViewController alloc] initWithTableStyle:UITableViewStyleGrouped];
// UIToolBar *myToolBar = [[UIToolBar alloc]initWithFrame:CGRectMake(0, 15, 320, 10)];
// CGRect *toolBarFrame;
// toolBarFrame = CGMakeRect (0, 440, 320, 40);
// [toolBarFrame setFrame:toolBarFrame];
// [myTableViewController.view addSubView:toolBarFrame];
//viewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"movies.jpg"]];
//myTableView.rowHeight=120;
[self.view addSubview:myTableView];
//tempArray = [[NSArray alloc] initWithObjects:#"Sports",#"News",#"naturals1",#"live",nil];
//titleArray = [[NSArray alloc] initWithObjects:#"SA spinners made the difference: Sammy",#"Cabinet terminates ISRO’s deal",#"Hudson River Fish Evolve Toxic ",#"Hi Today Special News?",nil];
//SBJSON *json = [SBJSON new];
// json.humanReadable = YES;
//self.tableDataList = tempArray;
//self.myTableView.backgroundColor = [UIColor clearColor];
//create new uiview with a background image
//UIImage *backgroundImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"movies" ofType:#"jpg"]];
//UIImageView *backgroundView = [[UIImageView alloc] initWithImage:backgroundImage];
//adjust the frame for the case of navigation or tabbars
//backgroundView.frame = CGRectMake(0, 0, 320, 460);
//add background view and send it to the back
//[self.viewController.view addSubview:backgroundView];
//[self.viewController.view sendSubviewToBack:backgroundView];
//[backgroundView release];
//UIImage *img1= [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://122.183.217.134:8080/sivajitv/photos/20101216001017.jpg"]]];
//NSLog(#"ERROR1:%#",img1);
//NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://122.183.217.134:8080/sivajitv/photos/20101216001017.jpg"]];
//NSLog(#"ERROR12:%#",imageData);
}
There are so many things wrong with your code it is hard to know where to begin:
client.connect; is syntactic sugar for [client connect], however since connect is not a property (at least I hope it is not a property), you should not use the dot-notation.
The argument to isEqualToString: expects an NSString * object, not NSNull *. If you want to see whether the variable points to a string (as opposed to nil), or, if you want to make sure that the string actually contains characters, use:
if ([main_str length])
// do something
You assign a new mutable array that you own to id_arr using id_arr=[[NSMutableArray alloc]init];, however you completely overwrite this reference later with id_arr=[[udf objectForKey:#"id_value"] componentsSeparatedByString:#","];. This means that the original array that you created (and own) can no longer be referenced, and is leaked.
You never initialise the object that you allocated:
js=[[JsontoObject alloc]sivajiTV_response:main_str];
You create an Event object, but never use it or release it (this is a memory leak):
e1=[[Event alloc]init];