iPhone refactoring with ivar names - iphone

Could anyone tell me how I can dynamically specify an ivar name within my method?
l2 is the ivar I'm trying to target.
//this works
if (maxunlocked > 1) {
filename = [NSString stringWithFormat:#"level%d.png", [[fliesArray objectAtIndex:2] intValue]];
filenameHi = [NSString stringWithFormat:#"level%dHi.png", [[fliesArray objectAtIndex:2] intValue]];
l2 = [SoundMenuItem itemFromNormalSpriteFrameName:filename selectedSpriteFrameName:filenameHi target:self selector:#selector(level:)];
}
//this doesn't
for (int i = 0; i<11; i++) {
if (maxunlocked > i) {
filename = [NSString stringWithFormat:#"level%d.png", [[fliesArray objectAtIndex:i] intValue]];
filenameHi = [NSString stringWithFormat:#"level%dHi.png", [[fliesArray objectAtIndex:i] intValue]];
//this is where I'm attempting to dynamically specify the SoundMenuItem instance name.
sndMenuItem = [NSString stringWithFormat:#"l%d", i];
sndMenuItem = [SoundMenuItem itemFromNormalSpriteFrameName:filename selectedSpriteFrameName:filenameHi target:self selector:#selector(level:)];
sndMenuItem.userData = (id)i;
}
}
Thanks,
Mark

If you have it declared as a property, you may be able to use KVC to get it.
float h1 = [object height];
float h2 = [[object valueForKey:#"height"] floatValue];
[EDIT]
I didn't understand what you're saying. The answer is no. You can't specify a variable name dynamically. What you can do is this:
// if `l2` is a member of self. (as in self.l2)
for (int i = 0; i<11; i++) {
if (maxunlocked > i) {
filename = [NSString stringWithFormat:#"level%d.png", [[fliesArray objectAtIndex:i] intValue]];
filenameHi = [NSString stringWithFormat:#"level%dHi.png", [[fliesArray objectAtIndex:i] intValue]];
//this is where I'm attempting to dynamically specify the SoundMenuItem instance name.
key = [NSString stringWithFormat:#"l%d", i];
tmp = [SoundMenuItem itemFromNormalSpriteFrameName:filename selectedSpriteFrameName:filenameHi target:self selector:#selector(level:)];
tmp.userData = (id)i;
[self setValue:tmp forKey:key];
}
}
[EDIT]
You should probably re-structure your entire class.
#interface myViewController: NSViewController {
UIButton *sound1;
UIButton *sound2;
SoundMenuItem *l1;
SoundMenuItem *l2;
}
#property (assign) IBOutlet UIButton *sound1; // connect up in IB
#property (assign) IBOutlet UIButton *sound2;
- (IBAction) clickSoundButton: (id)sender; // connect up to sound1 and sound2 in IB
- (SoundMenuItem) getSoundMenuItem: (int) i;
#end
#implementation myViewController
- (IBAction) clickSoundButton: (id)sender
{
if (sender == (id)sound1) l1 = [self getSoundMenuItem: 1];
if (sender == (id)sound2) l2 = [self getSoundMenuItem: 2];
}
- (SoundMenuItem) getSoundMenuItem: (int) i
{
if (maxunlocked <= i) return
NSString *filename = [NSString stringWithFormat:#"level%d.png", [[fliesArray objectAtIndex:i] intValue]];
NSString *filenameHi = [NSString stringWithFormat:#"level%dHi.png", [[fliesArray objectAtIndex:i] intValue]];
SoundMenuItem *sndMenuItem = [SoundMenuItem itemFromNormalSpriteFrameName:filename selectedSpriteFrameName:filenameHi target:self selector:#selector(level:)];
sndMenuItem.userData = (id)i;
return sndMenuItem; //(assuming it is auto-released)
}
#end

Sorry about the lack of info and thanks for your patience. I was struggling to add it all into the comments area due to the character limit.
This is what I'm attempting...
In my header file:
//SoundMenuItem is a class
SoundMenuItem *l1;
SoundMenuItem *l2; (I actually have 20 buttons, one for each game level)
In my .m file
//here I set up the l1 button which is never locked
l1 = [SoundMenuItem itemFromNormalSpriteFrameName:filename selectedSpriteFrameName:filenameHi target:self selector:#selector(level:)];
//and here I set the l2 button to be locked by default
l2 = [SoundMenuItem itemFromNormalSpriteFrameName:#"levellock.png" selectedSpriteFrameName:#"levellockHi.png" target:self selector:#selector(doNothing:)];
//now I check to see if level2 has been unlocked (maxunlocked > 1) and if so I reset the l2 instance to use different images.
if (maxunlocked > 1) {
filename = [NSString stringWithFormat:#"level%d.png", [[fliesArray objectAtIndex:2] intValue]];
filenameHi = [NSString stringWithFormat:#"level%dHi.png", [[fliesArray objectAtIndex:2] intValue]];
l2 = [SoundMenuItem itemFromNormalSpriteFrameName:filename selectedSpriteFrameName:filenameHi target:self selector:#selector(level:)];
}
So rather than having 20 iterations of the above if statement, one for each button I'm wanting to refactor it into one.
I hope I've made myself clearer.

After the question was clarified my first answer was not valid. The answer by #stephen with the suggestion for using a dictionary to keeping all the SoundMenuItem is what I would have proposed as well.

Related

how to update a string variable with another string variable

i have a string declare as such
NSString *str = [[NSString alloc] initWithFormat:#"I require an average GPA of at least %.2f to achieve my Goal of %# this semester - NTU GPA Calculator", pgagoal,(NSString *)[myPickerDelegate.myGoal objectAtIndex: [myPicker selectedRowInComponent:0]]];
i declared a global variable
NSStrinng *tweetString
and wants to copy the the string in str to tweetString. how should i copy it? since both are pointers, i tried:
tweetString = str;
or
tweetString = [NSString stringWithFormat:#"%#", str];
but it doest work.
EDIT:
my code:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex1{
NSLog(#"buttonindex 1 clicked");
NSString *str2;
NSLog(#"tweetString before if: %#", tweetString);
if (pgagoal < 0) {
NSString *str2 = [[NSString alloc] initWithFormat:#"Confirm, Guarantee, Chop and Stamp! I can achieve my Goal of %# this semester - NTU GPA Calculator", (NSString *)[myPickerDelegate.myGoal objectAtIndex: [myPicker selectedRowInComponent:0]]];
NSLog(#"tweetString: < 0 %#", str2);
}
else if (pgagoal > 5){
NSString *str2 = [[NSString alloc] initWithFormat:#"Its impossible!, i need an average GPA of at least %.2f to achieve %# this semester - NTU GPA Calculator", pgagoal,(NSString *)[myPickerDelegate.myGoal objectAtIndex: [myPicker selectedRowInComponent:0]]];
NSLog(#"tweetString: >5 %#", str2);
}
else{
NSString *str2 = [[NSString alloc] initWithFormat:#"I require an average GPA of at least %.2f to achieve my Goal of %# this semester - NTU GPA Calculator", pgagoal,(NSString *)[myPickerDelegate.myGoal objectAtIndex: [myPicker selectedRowInComponent:0]]];
NSLog(#"tweetString with else: %#", str2);
}
//did i update tweetString correctly?
tweetString = [NSString stringWithString:str2]; <-- stop working from this point EXC_BAD_ACCESS
NSLog(#"tweetString after if else: %#", tweetString);
[self sendEasyTweet:tweetString];
NSLog(#"tweetString: %#", tweetString);
[str2 release];
}
- (void)sendEasyTweet {
// Set up the built-in twitter composition view controller.
TWTweetComposeViewController *tweetViewController = [[TWTweetComposeViewController alloc] init];
// Set the initial tweet text. See the framework for additional properties that can be set.
[tweetViewController setInitialText:tweetString];
// Create the completion handler block.
[tweetViewController setCompletionHandler:^(TWTweetComposeViewControllerResult result) {
switch (result) {
case TWTweetComposeViewControllerResultCancelled:
// The cancel button was tapped.
NSLog(#"Tweet cancelled");
break;
case TWTweetComposeViewControllerResultDone:
// The tweet was sent.
NSLog(#"Tweet done");
break;
default:
break;
}
// Dismiss the tweet composition view controller.
[self dismissModalViewControllerAnimated:YES];
}];
// Present the tweet composition view controller modally.
[self presentModalViewController:tweetViewController animated:YES];
}
EDIT2:
Debbuger output:
2011-12-29 09:54:22.963 GPA[487:707] buttonindex 1 clicked
2011-12-29 09:54:22.966 GPA[487:707] tweetString before if: NTU GPA Calculator <-- i init the string at viewDidLoad
2011-12-29 09:54:22.968 GPA[487:707] tweetString with else: I require an average GPA of at least 1.56 to achieve my Goal of Third Class Honors this semester - NTU GPA Calculator
(gdb)
EDIT3:
my tweetString is declared in view controller.h as
#interface GPAMainViewController : UIViewController <GPAFlipsideViewControllerDelegate>{
UIPickerView * myPicker;
GPAAppDelegate * myPickerDelegate;
IBOutlet UITextField *txtGPA;
IBOutlet UITextField *txtTotalAU;
IBOutlet UITextField *txtRemainingAU;
double pgagoal;
NSString *tweetString;
}
#property (nonatomic, retain) IBOutlet UIPickerView * myPicker;
#property (nonatomic, retain) IBOutlet GPAAppDelegate *myPickerDelegate;
#property (nonatomic, retain) UITextField *txtGPA;
#property (nonatomic, retain) UITextField *txtTotalAU;
#property (nonatomic, retain) UITextField *txtRemainingAU;
#property (nonatomic, retain) NSString *tweetString;
-(IBAction)finishEditing:(id)sender;
-(IBAction)calculateGoal: (id) sender;
-(IBAction)showInfo:(id)sender;
-(IBAction)nextField:(id)sender;
-(IBAction)resetField:(id)sender;
-(void)sendEasyTweet:(id)sender;
The reason that it doesn't work (it is probably crashing with an EXC_BAD_ACCESS) is because the scope of the variable str is only within the block in which it is declared, the block of the else part of your if/else statement. Try something like this:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex1 {
NSString* str; //declare string here so it is in scope the entire method
.
. //your code
.
.
if(yourConditionHere) {
//make sure you initialize str here as well so if the else part of the statement
// isn't executed, you aren't trying to access an uninitialized variable
} else {
str = [[NSString alloc] initWithFormat:#"I require an average GPA of at
least %.2f to achieve my Goal of %# this semester - NTU GPA Calculator",
pgagoal,(NSString *)[myPickerDelegate.myGoal objectAtIndex: [myPicker
selectedRowInComponent:0]]]; //give str a value
NSLog(#"tweetString with else: %#", str);
} //Variable str is going out of scope here the way you have your code set up now
tweetString = [str copy];
NSLog(#"tweetString after if else: %#", tweetString);
[self sendEasyTweet:tweetString];
NSLog(#"tweetString: %#", tweetString);
[str release];
}
If you want to copy the string, or use the string after you assign it, you either need to copy it or retain it.
NSString *someString = #"This is a string";
NSString *copiedString = [NSString stringWithFormat:#"%#", someString"];
Within a few seconds, both strings will be nil or some other non value. What you must do is :
NSString *someString = #"This is a string";
NSString *copiedString = [NSString stringWithFormat:#"%#", someString"] retain];
By doing this, you will keep both variables in memory as long as they are viable. But in my opinion a better way, especially when dealing with strings is to use copy, like this :
NSString *someString = #"This is a string";
NSString *copiedString = [NSString stringWithFormat:#"%#", someString"] copy];
This will make someString just go away in a few seconds or clock ticks, but copiedString will live on until the function is finished or the class released.
I suspect that you are not getting the string value inside tweetString because both variables have gone from memory when you want to use it.
If you need a variable to stay around, you must copy or retain it.

How to display x raise to y in UIlabel

how can I display 5 raise to 1/3 in iphone i.e I want 1/3 written above 5 can anyone help please
I Found this solution, hope so it would be helpful for you.
x to the power of y in a UILabel could be easy. Just replace your indices with unicode superscript characters... I use the following method to turn an integer into a string with superscript characters.
+(NSString *)convertIntToSuperscript:(int)i
{
NSArray *array = [[NSArray alloc] initWithObjects:#"⁰", #"¹", #"²", #"³", #"⁴", #"⁵", #"⁶", #"⁷", #"⁸", #"⁹", nil];
if (i >= 0 && i <= 9) {
NSString *myString = [NSString stringWithFormat:#"%#", [array objectAtIndex:i]];
[array release];
return myString;
}
else {
NSString *base = [NSString stringWithFormat:#"%i", i];
NSMutableString *newString = [[NSMutableString alloc] init];
for (int b = 0; b<[base length]; b++) {
int temp = [[base substringWithRange:NSMakeRange(b, 1)] intValue];
[newString appendString:[array objectAtIndex:temp]];
}
[array release];
NSString *returnString = [NSString stringWithString:newString];
[newString release];
return returnString;
}
}
Try this NSString *cmsquare=#"cm\u00B2";
It will display cm².
Yes you can do that but you need custom UILabel, either Make it by yourself or Get it Open Source..

Memory Leak according to Instruments

Been running instruments on my app. Its says i am leaking 864bytes & 624bytes from 2 NSCFString and the library responsible is Foundation.
So that leads me to believe thats its not a leak caused by me? Or is it?
Here is the offending method according to instruments. It seems to be a
substringWithRange
that is leaking.
-(void) loadDeckData
{
deckArray =[[NSMutableArray alloc] init];
NSString* path = [[NSBundle mainBundle] pathForResource:#"rugby" ofType:#"txt"
inDirectory:#""];
NSString* data = [NSString stringWithContentsOfFile:path encoding:
NSUTF8StringEncoding error: NULL];
NSString *newString = #"";
NSString *newline = #"\n";
NSString *comma = #",";
int commaCount = 0;
int rangeCount = 0;
NSString *nameHolder = #"";
NSString *infoHolder = #"";
NSMutableArray *statsHolder = [[NSMutableArray alloc] init];
for (int i=0; i<data.length; i++)
{
newString = [data substringWithRange:NSMakeRange(i, 1)];
if ([newString isEqualToString: comma]) //if we find a comma
{
if (commaCount == 0)// if it was the first comma we are parsing the
NAME
{
nameHolder = [data substringWithRange:NSMakeRange(i-
rangeCount, rangeCount)];
}
else if (commaCount == 1)//
{
infoHolder = [data substringWithRange:NSMakeRange(i-
rangeCount, rangeCount)];
//NSLog(infoHolder);
}
else // if we are on to 2nd,3rd,nth comma we are parsing stats
{
NSInteger theValue = [[data
substringWithRange:NSMakeRange(i-rangeCount,rangeCount)]
integerValue];
NSNumber* boxedValue = [NSNumber
numberWithInteger:theValue];
[statsHolder addObject:boxedValue];
}
rangeCount=0;
commaCount++;
}
else if ([newString isEqualToString: newline])
{
NSInteger theValue = [[data substringWithRange:NSMakeRange(i-
rangeCount,rangeCount)] integerValue];
NSNumber* boxedValue = [NSNumber numberWithInteger:theValue];
[statsHolder addObject:boxedValue];
commaCount=0;
rangeCount=0;
Card *myCard = [[Card alloc] init];
myCard.name = nameHolder;
myCard.information = infoHolder;
for (int x = 0; x < [statsHolder count]; x++)
{
[myCard.statsArray addObject:[statsHolder
objectAtIndex:x]];
}
[deckArray addObject:myCard];
[myCard autorelease];
[statsHolder removeAllObjects];
}
else
{
rangeCount++;
}
}
[statsHolder autorelease];
}
Thanks for your advice.
-Code
As Gary's comment suggests this is very difficult to diagnose based on your question.
It's almost certainly a leak caused by you however, I'm afraid.
If you go to the View menu you can open the Extended Detail. This should allow you to view a stack trace of exactly where the leak occurred. This should help diagnose the problem.
When to release deckArray? If deckArray is a class member variable and not nil, should it be released before allocate and initialize memory space?

NSString's superclasses go on forever

I've got a method that when put a breakpoint in it and hover over a string, says it's out of scope and you can drill down into the NSString object for what seems like forever. I've tried to put a screen shot... hope it shows up. I think I have some serious memory management problems...
http://web.me.com/gazelips/Site/Blank_files/screenshot.jpg
Here's the whole .h and .m files. The problem occurs in the updateAdvice method.
#import <UIKit/UIKit.h>
#import "SourcePickerViewController.h"
#import "Chemical.h"
#interface AdjustViewController : UIViewController <SourcePickerViewControllerDelegate>{
// IB controls
UITextField *sourceField;
UITextField *volumeField;
UILabel *startingLabel;
UILabel *targetLabel;
UITextView *adviceLabel;
// Setup variables for the kind of chemical
int numberOfComponents;
NSDictionary *dictionaryOfSources;
// Local ivars
float percentRemove;
float gallonsRemove;
float selectedChemSourceAmount;
int delta;
NSString *selectedChemName;
NSString *selectedChemConcentration;
float selectedChemConstant;
BOOL selectedChemIsLiquid;
NSString *compositeName;
NSString *messageBody;
NSString *adviceMessage;
}
#property (nonatomic, retain) IBOutlet UITextField *sourceField;
#property (nonatomic, retain) IBOutlet UITextField *volumeField;
#property (nonatomic, retain) IBOutlet UILabel *startingLabel;
#property (nonatomic, retain) IBOutlet UILabel *targetLabel;
#property (nonatomic, retain) IBOutlet UITextView *adviceLabel;
#property (nonatomic, retain) NSString *selectedChemName;
#property (nonatomic, retain) NSString *selectedChemConcentration;
#property float selectedChemConstant;
#property BOOL selectedChemIsLiquid;
#property (nonatomic, retain) NSString *compositeName;
#property (nonatomic, retain) NSString *messageBody;
#property (nonatomic, retain) NSString *adviceMessage;
#property int numberOfComponents;
#property (nonatomic, retain) NSDictionary *dictionaryOfSources;
- (IBAction)backgroundTap:(id)sender;
//- (IBAction)textFieldDoneEditing:(id)sender;
- (IBAction)startingSliderChanged:(id)sender;
- (IBAction)startingSliderFinishedChanging;
- (IBAction)targetSliderChanged:(id)sender;
- (IBAction)targetSliderFinishedChanging;
- (IBAction)getChemicalSource;
- (void)updateAdvice;
#end
#import "AdjustViewController.h"
#implementation AdjustViewController
#synthesize sourceField;
#synthesize volumeField;
#synthesize startingLabel;
#synthesize targetLabel;
#synthesize adviceLabel;
#synthesize numberOfComponents;
#synthesize dictionaryOfSources;
#synthesize compositeName;
#synthesize messageBody;
#synthesize adviceMessage;
#synthesize selectedChemName;
#synthesize selectedChemConcentration;
#synthesize selectedChemConstant;
#synthesize selectedChemIsLiquid;
- (IBAction)backgroundTap:(id)sender {
[sourceField resignFirstResponder];
[volumeField resignFirstResponder];
[self updateAdvice];
}
- (IBAction)startingSliderChanged:(id)sender {
UISlider *slider = (UISlider *)sender;
int progressAsInt = (int)(slider.value + 0.5f);
NSString *newValue = [[NSString alloc] initWithFormat:#"%d", progressAsInt];
startingLabel.text = newValue;
[newValue release];
}
- (IBAction)targetSliderChanged:(id)sender {
UISlider *slider = (UISlider *)sender;
int progressAsInt = (int)(slider.value + 0.5f);
NSString *newValue = [[NSString alloc] initWithFormat:#"%d", progressAsInt];
targetLabel.text = newValue;
[newValue release];
}
- (IBAction)startingSliderFinishedChanging {
// [self updateAdvice];
}
- (IBAction)targetSliderFinishedChanging {
// [self updateAdvice];
}
// Present the picker for chlorine selection
- (IBAction)getChemicalSource {
SourcePickerViewController *sourcePickerViewController = [[SourcePickerViewController alloc] init];
sourcePickerViewController.delegate = self;
NSLog(#"getChemicalSource setting numberOfComponents %d", self.numberOfComponents);
sourcePickerViewController.numberOfComponents = self.numberOfComponents;
NSLog(#"getChemicalSource sending numberOfComponents %d", sourcePickerViewController.numberOfComponents);
sourcePickerViewController.dictionaryOfSources = self.dictionaryOfSources;
[self presentModalViewController:sourcePickerViewController animated:YES];
[sourcePickerViewController release];
}
- (void)updateAdvice {
NSLog(#"--updateAdvice");
NSLog(#" selectedChemical name = %#", selectedChemName);
NSLog(#" selectedChemical concentration = %#", selectedChemConcentration);
NSLog(#" selectedChemical constant = %1.6f", selectedChemConstant);
NSLog(#" selectedChemical is liquid = %d", selectedChemIsLiquid);
// First check to see if there is a source AND volume, otherwise prompt user to enter them
if ([volumeField.text isEqualToString:#""] || [sourceField.text isEqualToString:#""]) {
adviceMessage = #"Enter a source and volume.";
}
// If there IS a source and volume, calculate!
else {
if ([selectedChemConcentration isEqualToString:#""]) { // If there's no concentration, make a string with just the name
compositeName = selectedChemName;
NSLog(#" compositeName without concentration = %#", compositeName);
}
else { // But if there is a concentration, make a string with the name and concentration and a space between.
compositeName = [[NSString alloc] initWithFormat:#"%# %#", selectedChemName, selectedChemConcentration];
NSLog(#" compositeName with concentration = %# %#", compositeName, selectedChemConcentration);
}
delta = [targetLabel.text intValue] - [startingLabel.text intValue]; // The difference between target and starting levels
NSLog(#" delta = %d", delta);
sourceAmount = delta * [volumeField.text intValue] * sourceConstant; // Calculates the amount of source chemical necessary in ounces
NSLog(#" sourceAmount = %1.1f", sourceAmount);
// If delta is positive, add chemical
if (delta > 0) {
NSLog(#">> Delta > 0");
if (selectedChemIsLiquid) {
if (sourceAmount > 128) { // Amount is more than a gallon
sourceAmount = sourceAmount / 128;
messageBody = [[NSString alloc] initWithFormat:#"To increase %# by %d ppm, add %1.1f gal of ", self.title, delta, sourceAmount];
}
else { // Less than a gallon
messageBody = [[NSString alloc] initWithFormat:#"To increase %# by %d ppm, add %1.1f fl oz of ", self.title, delta, sourceAmount];
}
}
else { // Chemical is a solid
if (sourceAmount > 16) { // Amount is more than a pound
sourceAmount = sourceAmount / 16;
messageBody = [[NSString alloc] initWithFormat:#"To increase %# by %d ppm, add %1.1f lb of ", self.title, delta, sourceAmount];
}
else { // Less than a pound
messageBody = [[NSString alloc] initWithFormat:#"To increase %# by %d ppm, add %1.1f oz of ", self.title, delta, sourceAmount];
}
}
adviceMessage = [[NSString alloc] initWithFormat:#"%#%#.", messageBody, compositeName];
}
// If delta is zero, stay the course
if (delta == 0) {
NSLog(#"== Delta = 0");
adviceMessage = #"You're on target. No action necessary.";
}
// If delta is negative, remove water
if (delta < 0) {
NSLog(#"<< Delta < 0");
adviceMessage = #"You're over target. Remove some water.";
}
}
adviceLabel.text = adviceMessage; // Set the advice label
[messageBody release]; // And get rid of message
[compositeName release];
[adviceMessage release];
}
- (void)viewDidLoad {
NSLog(#"AdjustViewController launched");
sourceField.text = #"";
adviceLabel.text = #"";
percentRemove = 0;
gallonsRemove = 0;
delta = 0;
selectedChemSourceAmount = 0;
// [self updateAdvice];
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
sourceField = nil;
volumeField = nil;
startingLabel = nil;
targetLabel = nil;
adviceLabel = nil;
dictionaryOfSources = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[sourceField release];
[volumeField release];
[startingLabel release];
[targetLabel release];
[adviceLabel release];
[dictionaryOfSources release];
[super dealloc];
}
#pragma mark -
#pragma mark Picker View Delegate Methods
// Returns the values from the picker if a source was chosen
- (void)sourcePickerViewController:(SourcePickerViewController *)controller
didSelectSource:(NSString *)source
andConcentration:(NSString *)concentration
andConstant:(float)constant
andIsLiquid:(BOOL)isLiquid {
selectedChemName = source;
selectedChemConcentration = concentration;
selectedChemConstant = constant;
selectedChemIsLiquid = isLiquid;
// Update the source textfield. If concentration is empty, just use the source otherwise concatenate them
if ([selectedChemConcentration isEqualToString:#""]) {
sourceField.text = [[NSString alloc] initWithFormat:#"%#", selectedChemName];
}
else {
sourceField.text = [[NSString alloc] initWithFormat:#"%# %#", selectedChemName, selectedChemConcentration];
}
// [self updateAdvice];
NSLog(#"Returned source = %#, concentration = %#, constant = %1.7f, isLiquid = %d", source, concentration, constant, isLiquid);
NSLog(#"selectedChemical.chemName = %#, chemConcentration = %#, chemConstant = %1.7f, chemIsLiquid = %d", selectedChemName, selectedChemConcentration, selectedChemConstant, selectedChemIsLiquid);
[self dismissModalViewControllerAnimated:YES];
}
// Returns from the picker without choosing a new source
- (void)sourcePickerViewController:(SourcePickerViewController *)controller
didSelectCancel:(BOOL)didCancel {
// [self updateAdvice];
NSLog(#"Returned without selecting source");
[self dismissModalViewControllerAnimated:YES];
}
#end
What you're seeing there is not an infinite chain of superclasses (if you look at the actual address you'll see it does not change after the second time), you're actually looking at the NSObject metaclass. Have a quick read through that link—wonderfully provided by Matt Gallagher—and it will explain what you're seeing in the debugger. NSObject's metaclass's metaclass is itself.
This is actually quite common and not necessarily anything to do with a bug in your code.
If you right click on the string object in the debugger window and select "print description to console", it should work just fine.
I'm just looking at your code anyway. What the other two people said hold... however, memory management issues:
if (sourceAmount > 16) { // Amount is more than a pound
sourceAmount = sourceAmount / 16;
messageBody = [[NSString alloc] initWithFormat:#"To increase %# by %d ppm, add %1.1f lb of ", self.title, delta, sourceAmount];
}
else { // Less than a pound
messageBody = [[NSString alloc] initWithFormat:#"To increase %# by %d ppm, add %1.1f oz of ", self.title, delta, sourceAmount];
}
[...]
[messageBody release]; // And get rid of message
[compositeName release];
[adviceMessage release];
I think it would be better for you to simply write
self.messageBody = [NSString stringWithFormat:#"To increase %#...", self.title];
This automatically invokes the accessor methods which you synthesized using #synthesize messageBody.
It will automatically release the old string, and retain the new one.
What you are doing right now is allocating a new string without releasing the old string. And why do that yourself when you have already synthesized the accessor methods?
Finally, don't forget to properly release the messageBody in dealloc, where you should be releasing it.
- (void)dealloc
{
[messageBody release];
[everythingElseIHaveToRelease release];
[super dealloc];
}
Hope that helps!
H

build and analyze not working in my project

In my iPhone Project when i select build and analyze (shift + mac + A ) it will give me all potential memory leak in my project... but in my current project it is not working... when i intentionally put a memory leak and select build and analyze... it doesn't give me any potential memory leak as analyzer result
if i write
NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:6];
NSMutableArray *tempArrayfinal = [[NSMutableArray alloc] initWithCapacity:12];
and doesn't release it... it is not giving me any potential leak but if i write
NSString *leakyString = [[NSString alloc] initWithString:#"Leaky String "];
NSLog(#"%#",leakyString);
here it gives me potential leak as analyzer result...why it is not giving potential leak in NSMutableArray and why it gives potential leak in NSString ?... how can i rely on Build and analyze for memory leak...
I've run the app with Leak tool and it is showing me leak in tempArray and tempArrayfinal
Here is my function
- (void)viewDidLoad
{
[super viewDidLoad];
maxOnSnaxAppDelegate *delegate = (maxOnSnaxAppDelegate *)[[UIApplication sharedApplication] delegate];
lblMessage.tag = MESSAGE_LABEL;
lblGuess.tag = GUESS_LABEL;
lblScore.tag = SCORE_LABEL;
self.gameCompleteView.tag = FINAL_SCORE_VIEW;
lblFinalScore.tag = FINAL_SCORE_LABEL;
lblGuess.text = #"";
lblMessage.text = #"";
lblScore.text = #"";
int row = 0;
int column = 0;
maxImagrArray = [[NSMutableArray alloc] init];
for(UIView *subview in [self.view subviews]) {
if([subview isKindOfClass:[CustomImageView class]])
{
[subview removeFromSuperview];
}
}
for(int i = 0 ; i < 12 ; i++)
{
if(i%3 == 0 && i != 0)
{
row++;
column = -1;
}
if(i != 0 )
{
column++;
//row = 0;
}
CustomImageView *tempImageView = [[CustomImageView alloc] initWithImage:[UIImage imageNamed:#"max-img.png"]];
tempImageView.frame = CGRectMake((column*tempImageView.frame.size.width) + 45, (row*tempImageView.frame.size.height)+ 60, tempImageView.frame.size.width, tempImageView.frame.size.height);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, tempImageView.bounds);
[self.view addSubview:tempImageView];
tempImageView.tag = i+1;
tempImageView.userInteractionEnabled = YES;
[maxImagrArray addObject:tempImageView];
[tempImageView setIndex:i];
[tempImageView release];
}
NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:6];
NSMutableArray *tempArrayfinal = [[NSMutableArray alloc] initWithCapacity:12];
for(int i = 0 ; i < 12 ; i++)
{
if(i < 6)
{
int temp = (arc4random() % 10) + 1;
NSString *tempStr = [[NSString alloc] initWithFormat:#"%d",temp];
[tempArray insertObject:tempStr atIndex:i];
[tempArrayfinal insertObject:tempStr atIndex:i];
[tempStr release];
}
else
{
int temp = (arc4random() % [tempArray count]);
[tempArrayfinal insertObject: (NSString *)[tempArray objectAtIndex:temp] atIndex:i];
//int index = [(NSString *)[tempArray objectAtIndex:temp] intValue];
[tempArray removeObjectAtIndex:temp];
}
CustomImageView *tmpCustom = [maxImagrArray objectAtIndex:i];
tmpCustom.frontImageIndex = [(NSString *)[tempArrayfinal objectAtIndex:i] intValue];
NSLog(#"%d",tmpCustom.frontImageIndex);
}
[maxImagrArray release];
delegate.time = 60.0;
timer = nil;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(countDown) userInfo:nil repeats:YES];
delegate.view = self.view;
//[tempArray release];
//[tempArrayfinal release];//these 2 lines are deliberately commented to see
//...it is not showing any potential memory leak though....
delegate.viewController = self;
}
please help...
[tempArray insertObject:tempStr atIndex:i];
[tempArrayfinal insertObject:tempStr atIndex:i];
are the culprits... when i uncomment these 2 lines.. it stops giving me the warning... i don't know why...
You shouldn't really rely on the Build and Analyze tool. It does not always catch all leaks. Threre is no substitute for following the memory management rules from apple (apart from garbage collection on OS X). However, I'm not sure why it isn't catching such a simple leak. I tried at line in a method and it did give me a result. Are you sure its not in an if statement, because I've found that sometimes in an if statement it won't correct you.