Dead code with Xcode anaylser - ios

i wanted to analyse my projet, and xcode analyser find some Dead Code in my rootcontroller
Xcode tell me that :
Dead code
The left operand to '+' is always 0
-> Variable 'i' initialized to 0
-> The left operand to '+' is always 0
Can someone explain me this ans how to clean that code, thanks....
here is my rootcontroller.m
#import "RootViewController22.h"
#import "LabelCell.h"
#import "NibLoadedCell.h"
#import "GradientBackgroundTable.h"
#import "NibLoadedCell2.h"
#import "NibLoadedCell3.h"
#implementation RootViewController22
//
// title
//
// returns the navigation bar text for the front screen
//
/*- (NSString *)title
{
return NSLocalizedString(#"Les Robes du Bengal", #"");
}*/
//
// createRows
//
// Constructs all the rows on the front screen and animates them in
//
- (void)createRows
{
[self addSectionAtIndex:0 withAnimation:UITableViewRowAnimationFade];
for (NSInteger i = 0; i < 1; i++)
{
[self
appendRowToSection:0
cellClass:[NibLoadedCell2 class]
cellData:[NSString stringWithFormat:
NSLocalizedString(#"This is row %ld", #""), i + 1]
withAnimation:(i % 2) == 0 ?
UITableViewRowAnimationLeft :
UITableViewRowAnimationRight];
}
//[self addSectionAtIndex:0 withAnimation:UITableViewRowAnimationFade];
//for (NSInteger i = 0; i < 4; i++)
//{
// [self
// appendRowToSection:0
// cellClass:[LabelCell class]
// cellData:[NSString stringWithFormat:
// NSLocalizedString(#"This is row %ld", #""), i + 1]
// withAnimation:(i % 2) == 0 ?
// UITableViewRowAnimationLeft :
// UITableViewRowAnimationRight];
// }
[self addSectionAtIndex:1 withAnimation:UITableViewRowAnimationFade];
for (NSInteger i = 0; i < 1; i++)
{
[self
appendRowToSection:1
cellClass:[NibLoadedCell3 class]
cellData:[NSString stringWithFormat:
NSLocalizedString(#"This is row %ld", #""), i + 1]
withAnimation:(i % 2) == 0 ?
UITableViewRowAnimationLeft :
UITableViewRowAnimationRight];
}
// [self addSectionAtIndex:2 withAnimation:UITableViewRowAnimationFade];
// for (NSInteger i = 0; i < 4; i++)
// {
// [self
// appendRowToSection:2
// cellClass:[TextFieldCell class]
// cellData:
// [NSMutableDictionary dictionaryWithObjectsAndKeys:
// [NSString stringWithFormat:
// NSLocalizedString(#"TextField %ld", #""), i + 1],
// #"label",
// #"", #"value",
// NSLocalizedString(#"Value goes here", #""),
// #"placeholder",
// nil]
// withAnimation:(i % 2) == 0 ?
// UITableViewRowAnimationLeft :
// UITableViewRowAnimationRight];
// }
[self addSectionAtIndex:2 withAnimation:UITableViewRowAnimationFade];
for (NSInteger i = 0; i < 1; i++)
{
[self
appendRowToSection:2
cellClass:[NibLoadedCell class]
cellData:[NSString stringWithFormat:
NSLocalizedString(#"This is row %ld", #""), i + 1]
withAnimation:(i % 2) == 0 ?
UITableViewRowAnimationLeft :
UITableViewRowAnimationRight];
}
[self hideLoadingIndicator];
}
//
// refresh
//
// Removes all existing rows and starts a reload (on a 0.5 second timer)
//
- (void)refresh:(id)sender
{
[self removeAllSectionsWithAnimation:UITableViewRowAnimationFade];
[self performSelector:#selector(createRows) withObject:nil afterDelay:0.5];
[self showLoadingIndicator];
}
//
// viewDidLoad
//
// On load, refreshes the view (to load the rows)
//
- (void)viewDidLoad
{
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
self.title = #"Les Robes";
[super viewDidLoad];
self.useCustomHeaders = YES;
[self refresh:nil];
}
//
// loadView
//
// Since the view is so simple (just a GradientBackgroundView) we might as
// well contruct it in code.
//
- (void)loadView
{
GradientBackgroundTable *aTableView =
[[[GradientBackgroundTable alloc]
initWithFrame:CGRectZero
style:UITableViewStyleGrouped]
autorelease];
self.view = aTableView;
self.tableView = aTableView;
}
//
// textFieldDidEndEditing:
//
// Update the rowData for the text field rows to match the edited value of the
// text field.
//
//
// tableView:titleForHeaderInSection:
//
// Header text for the three sections
//
// Parameters:
// aTableView - the table
// section - the section for which header text should be returned
//
// returns the header text for the appropriate section
//
- (NSString *)tableView:(UITableView *)aTableView
titleForHeaderInSection:(NSInteger)section
{
if (section == 0)
{
return NSLocalizedString(#"Les Motifs", nil);
}
else if (section == 1)
{
return NSLocalizedString(#"Les Couleurs", nil);
}
else if (section == 2)
{
return NSLocalizedString(#"À Savoir", nil);
}
return nil;
}
#end

In your createRows method, you have a loop that will only execute once:
for (NSInteger i = 0; i < 1; i++) { ... }
Therefore, things like i + 1 and i % 2 could just be constants since i will always be 0.

for (NSInteger i = 0; i < 1; i++)
Your for loop starts at 0, ends at 0. i++ will never be executed.

You've got several loops of the form:
for (NSInteger i = 0; i < 1; i++) { }
That code is nearly meaningless, though... the code in the body of the loop will only ever execute once, while i == 0, so you might as well just take it out of the loop.

Related

How to make custom completion Handler with Objective-C

I've looked through various documents, but don't know how to apply the completion handler in the following cases.
//example function.
//default textView height 100.0f
-(void)getHeightResult{
[self initHeight];
NSLog(#"%#", [self setTextManager]);
}
-(NSString *)setTextManager{
if(self.textView.frame.size.heigh != 100){
return #"new Height";
} else{
return #"Default Height;
}
}
-(void)initHeight{
int result;
for(int i = 0 ; i <= 20: i ++){
result = result + i;
}
//result = 210
self.textView.frame.size.height = result;
}
When executing the above functions, getHeightResult always outputs 'Default Height'.
How can I apply a Completion Handler to get it returned as the value calculated in initHeight from a source like this?
We ask for answers to help you understand the Completion Handler, not for asking the actual source.
Code for completionHandler,
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self getSize:^(bool status) {
if (status == true) {
// perofm your operioan
NSLog(#"Done");
}
}];
}
typedef void (^CompletionBlock)(_Bool status);
-(void)getSize:(CompletionBlock)block{
__block int count = 0;
[self initWidth:^(bool status) {
count++;
if (count == 2) {
block(true);
}
}];
[self initHeight:^(bool status) {
count++;
if (count == 2) {
block(true);
}
}];
}
-(void)initHeight:(CompletionBlock)block{
int result;
for(int i = 0 ; i <= 100; i ++) {
result = result + i;
}
block(true);
}
-(void)initWidth:(CompletionBlock)block{
int result;
for(int i = 0 ; i <= 20; i ++){
result = result + i;
}
block(true);
}

how to get the uibutton state value in test.m file

In .m file i have methods like
-(void) textdata
{
long i = search.text.length;
if (i > 0) {
searchButton.enabled = YES;
}
else
{
searchButton.enabled = NO;
}
[self buttonstate];
}
-(int) buttonstate
{
if ([searchButton isEnabled]) {
j = 1;
}
else
j = 0;
NSLog(#" j value is %d",j);
return j;
}
- (void) textFieldDidChange
{
[self textdata];
NSLog(#"test data is %#",search.text);
}
And in the tests.m file i have test like
-(void) testwithoutData
{
myapiViewController *apiViw = [[myapiViewController alloc]init];
[apiViw textdata];
int kn = [apiViw buttonstate];
NSLog(#"the value is %ld",(long)kn);
}
You have to do alloc init because due to this instance variable getting nil. Try this -
In ViewController.m -
-(int) buttonstate {
long i = self.searchTxt.text.length;
if (i > 0) {
self.searchBtn.enabled = YES;
}
else
{
self.searchBtn.enabled = NO;
}
if ([self.searchBtn isEnabled]) {
j = 1;
}
else
j = 0;
NSLog(#" j value is %d",j);
return j;
}
In ViewControllerTests.m -
- (void)testExample {
// This is an example of a functional test case.
XCTAssert(YES, #"Pass");
self.vcToTest.searchTxt = [[UITextField alloc] init];
self.vcToTest.searchBtn = [[UIButton alloc] init];
self.vcToTest.searchTxt.text = #"test";
int kn = [self.vcToTest buttonstate];
NSLog(#"the value is %ld",(long)kn);
}
Check the attached screenshot output -

UILabel does not update each time with for loop

I'm trying to animate my label in my UICollectionViewCell. I want to go randomly through the array and set the label randomly 10 times and then it stops at a random string from my array.
The problem is, it goes through my array (debugged it with a simple NSLog) BUT the label setText isn't used till the last number of my loop and the label is then set.
Here is my code:
-(void)animate{
long index;
for(detail* cells in [[self col] visibleCells]){
NSIndexPath *indexPath = [[self col] indexPathForCell:cells];
if ([array count] >= 3) {
index = 2 * indexPath.section + indexPath.row;
}else{
index = 1 * indexPath.section + indexPath.row;
}
for (int i = 0; i <= 10; i++) {
[[cells detailLabel] setText: [[array objectAtIndex:index] returnRandomOptie]];
[NSThread sleepForTimeInterval:0.10];
NSLog(#"%i", i);
}
}
}
And here is my returnRandomOptie from my custom Cell class:
-(NSString *) returnRandomOptie {
NSUInteger randomIndex;
NSString *string;
if ([opties count] != 0) {
randomIndex = arc4random() % [opties count];
string = [NSString stringWithFormat:#"%#", [opties objectAtIndex:randomIndex]];
}
return string;
}
So basically I want that the for loop in my animate method, always sets the text in my label. And now it doesn't do that. Just at the last loop.
What am I doing wrong?
Kind Regards!
You have to perform the sleep async and update the label in the main thread, try this instead :
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i <= 10; i++) {
dispatch_async(dispatch_get_main_queue(), ^{
[[cells detailLabel] setText: [[array objectAtIndex:index] returnRandomOptie]];
});
[NSThread sleepForTimeInterval:0.10];
NSLog(#"%i", i);
}
});
Try this,
-(void)animate{
....
for (int i = 0; i <= 10; i++) {
dispatch_async(dispatch_get_main_queue(), ^{
[[cells detailLabel] setText: [[array objectAtIndex:index] returnRandomOptie]];
});
[NSThread sleepForTimeInterval:0.10];
NSLog(#"%i", i);
}
...
}

iOS: Setting variables on several custom view objects

Okay, so I'm creating X number of a custom UIView, that I've created in IB...
I create them in a grid-like formation and need to set their individual properties based on a response from a web service call...
The part I'm having trouble with is how to iterate through the different UIViews and set the variables...
I'm pretty sure the solution is really simple, but I've been staring blindly at this for some time now...
It's the part after:
if([theStatus.groupName isEqualToString:groupEntry.groupNameLabel.text])
{
Here is the entire method:
- (void)receivedGroups
{
int rows, columns;
if([groupConnection.groupsArray count] <= 4)
{
rows = 1;
columns = [groupConnection.groupsArray count];
} else if([groupConnection.groupsArray count] >= 5 && [groupConnection.groupsArray count] <= 8)
{
rows = 2;
columns = ([groupConnection.groupsArray count] + 1 )/ 2;
} else
{
rows = 3;
columns = ([groupConnection.groupsArray count] + 2 )/ 3;
}
int number = 0;
for(int j=1; j < columns+1; j++)
{
for(int k=0; k < rows; k++)
{
// Only create the number of groups that match the number of entries in our array
if(number < [groupConnection.groupsArray count])
{
// Create an instance of the group view
GroupEntry *groupEntry = [[GroupEntry alloc] initWithFrame:CGRectMake(230*j, 250*k, 180, 233)];
// Add it to the view
[self.view addSubview:groupEntry];
// Get the group
GetGroupsActive *theGroups = [groupConnection.groupsArray objectAtIndex:number];
groupEntry.groupNameLabel.text = theGroups.groupName;
for(int i=0; i<[statusConnection.statusArray count]; i++)
{
CurrentStatus *theStatus = [statusConnection.statusArray objectAtIndex:i];
if([theStatus.groupName isEqualToString:groupEntry.groupNameLabel.text])
{
//allChildren++;
switch(theStatus.currentStatus)
{
case 0:
//childrenSick++;
break;
case 1:
//childrenVacation++;
break;
case 2:
//childrenPresent++;
break;
case 3:
//childrenOut++;
break;
case 4:
//childrenTour++;
break;
default:
break;
}
}
}
NSString *allLabelText = [NSString stringWithFormat:#"%i", allChildren];
NSString *sickLabelText = [NSString stringWithFormat:#"%i", childrenSick];
NSString *vacationLabelText = [NSString stringWithFormat:#"%i", childrenVacation];
NSString *presentLabelText = [NSString stringWithFormat:#"%i", childrenPresent];
NSString *outLabelText = [NSString stringWithFormat:#"%i", childrenOut];
NSString *tripLabelText = [NSString stringWithFormat:#"%i", childrenTour];
groupEntry.sickLabelNumber.text = sickLabelText;
groupEntry.presentLabelNumber.text = presentLabelText;
groupEntry.numberLabelNumber.text = allLabelText;
groupEntry.tripLabelNumber.text = tripLabelText;
groupEntry.outLabelNumber.text = outLabelText;
groupEntry.vacationLabelNumber.text = vacationLabelText;
// Create the buttons to handle button press
UIButton *childButton = [UIButton buttonWithType:UIButtonTypeCustom];
childButton.frame = CGRectMake(230*j, 250*k, 180, 233);
// Set an identity tag, so we can recognize it during button press
childButton.tag = theGroups.ID;
// When EventTouchUpInside, send an action to groupSelected:
[childButton addTarget:self action:#selector(groupSelected:) forControlEvents:UIControlEventTouchUpInside];
// Add it to the view
[self.view addSubview:childButton];
}
number++;
}
}
}
If you added all the views in a parent view. You can get all the subviews using,
NSAarry *subviews = [base subviews];
for(UIView *subview in subviews)
{
subview.property = yourVaule;
}
You can differentiate between subviews using its tag or another property.

targetValue, score don't appear in outlets for the view

Have been working on single view game, which includes targetValue and score, both of which should appear in the outlets in the view. Connected them to the view controller (File's Owner) in IB, and the targetValue used to appear, but now, after adding some code, it doesn't appear anymore.
What's wrong?
Here is the code from BullseyeViewController.m:
#import "BullsEyeViewController.h"
#implementation BullsEyeViewController {
int currentValue;
int targetValue;
int score;
}
#synthesize slider;
#synthesize targetLabel;
#synthesize scoreLabel;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)updateLabels
{
self.targetLabel.text = [NSString stringWithFormat:#"%d", targetValue];
self.scoreLabel.text = [NSString stringWithFormat:#"%d",score];
}
- (void)startNewRound
{
targetValue = 1 + (arc4random() % 100);
currentValue = self.slider.value;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self startNewRound];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.slider = nil;
self.targetLabel = nil;
self.scoreLabel = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}
- (IBAction)showAlert
{
int difference = abs(targetValue - currentValue);
int points = 100 - difference;
score += points;
NSString *title;
if (difference == 0) {
title = #"Perfect!";
points += 100;
} else if (difference < 5) {
if (difference == 1) {
points += 50;
}
title = #"You almost had it!";
} else if (difference < 10) {
title = #"Pretty good!";
} else {
title = #"Not even close...";
}
NSString *message = [NSString stringWithFormat:#"You scored %d points", points];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertView show];
}
- (IBAction)sliderMoved:(UISlider *)slider
{
currentValue = lroundf(slider.value);
}
#end
if you set a breakpoint on updateLabels, does it ever hit?
Also, change your updateLabels method to look like this:
- (void)updateLabels
{
targetLabel.text = [NSString stringWithFormat:#"%d", targetValue];
scoreLabel.text = [NSString stringWithFormat:#"%d",score];
}
Do you refer to these labels from outside of your view controller? If not, do they need to be properties?

Resources