UILabel with iOS Storyboard: I can set the text explicitly, but introduce stringWithFormat: can't set text - nsstring

This is a weird one. I've got a label on my storyboard in a custom prototype cell whose tag is 102. As the subject title suggests, I can set the text of the label in various ways and it appears on the device as expected. Here are the methods I've tried that work:
nameLabel.text = #"My buddy's name";
nameLabel.text = [[self.matchArray objectAtIndex:indexPath.row] valueForKey:#"player2Username"];
[nameLabel setText:[[self.matchArray objectAtIndex:indexPath.row] valueForKey:#"player2Username"]];
These, however, don't work...
NSString *nameString = [NSString stringWithFormat:#"game with %#", [[self.matchArray objectAtIndex:indexPath.row] valueForKey:#"player2Username"]];
[nameLabel setText:nameString];
also...
[nameLabel setText:[NSString stringWithFormat:#"game with %#", [[self.matchArray objectAtIndex:indexPath.row] valueForKey:#"player2Username"]]];
and...
nameLabel.text = [NSString stringWithFormat:#"game with %#", [[self.matchArray objectAtIndex:indexPath.row] valueForKey:#"player2Username"]];
I need for the cells to read: "game with so-and-so" where "so-and-so" is the opponent's name, obviously. Any ideas as to what would cause this?
EDIT: So here's some more code, demonstrating how I'm attacking this thing:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MatchCell"];
UILabel *nameLabel = (UILabel *)[cell viewWithTag:102];
...
}
if (indexPath.section == 0) {
nameLabel.text = [[self.matchArray objectAtIndex:indexPath.row] valueForKey:#"player2Username"];
[nameLabel setText:[[self.matchArray objectAtIndex:indexPath.row] valueForKey:#"player2Username"]];
NSString *nameString = [NSString stringWithFormat:#"game with %#", [[self.matchArray objectAtIndex:indexPath.row] valueForKey:#"player2Username"]];
[nameLabel setText:nameString];
[nameLabel setText:[NSString stringWithFormat:#"game with %#", [[self.matchArray objectAtIndex:indexPath.row] valueForKey:#"player2Username"]]];
nameLabel.text = [NSString stringWithFormat:#"game with %#", [[self.matchArray objectAtIndex:indexPath.row] valueForKey:#"player2Username"]];
}
return cell;
}
I'm using Parse as my BaaS. There really doesn't seem to be a problem there, as I can retrieve, log, and display on my iPhone (in the cell) the player's username and any other data I want, as long as I don't incorporate stringWithFormat:.
I tried cleaning the project and the build folder, uninstalling from the device, etc. Re-ran it. Still no luck.

Newb mistake. I didn't size the UILabel wide enough to accommodate the extra text. That is to say I could explicitly set a string (e.g. nameLabel.text = #"player name";) and there was enough room to fit the player's name, but whenever I tried to prepend "game with " to any user's name, it had the effect of making the entire string too long for the small width of the UILabel to accommodate. So, I guess it was reverting to the text of the label (which I had set in Interface Builder/Storyboard), "game with...".
In a nutshell, be sure you make your UILabels wide enough to accommodate the text they're going to be handling, kids! If you don't, someone's gonna wind up with a disease or pregnant or worse. I've seen it a thousand times.

Related

watchkit WKAlertAction openSystemURL

I am trying to show the User different Phone Numbers on Apple Watch and he clicks on one than phone call alert should appear. I'll do it like this but the Alert is just dismissed without call action:
NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:0];
WKExtension *myExt = [WKExtension sharedExtension];
for (NSString *phone in arr) {
NSString *tel = [NSString stringWithFormat:#"tel:%#",phone];
WKAlertAction *act = [WKAlertAction actionWithTitle:tel style:WKAlertActionStyleDefault handler:^(void){
[myExt openSystemURL:[NSURL URLWithString:phone1]];
}];
[tempArray addObject:act];
}
NSString *titleMessage = #"Call";
NSString *textMessage = #"Please select the number you want to call.";
NSString *cancel = #"Cancel";
WKAlertAction *act = [WKAlertAction actionWithTitle:cancel style:WKAlertActionStyleDestructive handler:^(void){
}];
[tempArray addObject:act];
[self presentAlertControllerWithTitle:titleMessage message:textMessage preferredStyle:WKAlertControllerStyleAlert actions:tempArray];
Buttons are shown as expected and the Handler is also called with the correct Phone Number. But it does not openSystemURL. Does somebody know why and how to fix? Thanks!
I think you forgot to add "tel" scheme ,Use below code :
[WKAlertAction actionWithTitle:#"tel" style:WKAlertActionStyleDefault handler:^(void){
[[WKExtension sharedExtension]openSystemURL:[NSURL URLWithString:[NSString stringWithFormat:#"tel:%#",#"YOUR NUMBER"]]];
}];
About Apple URL Schemes

How can I change (modify) video frame rate and bit rate?

I need re-encoding a video file from photo library for web site service.
I tried below code but it has occurred error like 'video composition must have composition instructions'.
(code)
AVAsset *anAsset = [[AVURLAsset alloc] initWithURL:videoFileUrl options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:anAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
self.exportSession = [[AVAssetExportSession alloc]
initWithAsset:anAsset presetName:AVAssetExportPresetPassthrough];
AVMutableComposition* mixComposition = [[AVMutableComposition alloc] init];
AVMutableCompositionTrack *firstTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
[firstTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, anAsset.duration) ofTrack:[[anAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:kCMTimeZero error:nil];
AVMutableVideoCompositionLayerInstruction *FirstlayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:firstTrack];
AVMutableVideoCompositionInstruction * MainInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
MainInstruction.layerInstructions = [NSArray arrayWithObjects:FirstlayerInstruction,nil];
AVMutableVideoComposition *MainCompositionInst = [AVMutableVideoComposition videoComposition];
MainCompositionInst.frameDuration = CMTimeMake(1, 30); // bit rate
MainCompositionInst.renderSize = CGSizeMake(640, 480); // frame rate
[self.exportSession setVideoComposition:MainCompositionInst];
NSURL *furl = [NSURL fileURLWithPath:self.tmpVideoPath];
self.exportSession.outputURL = furl;
self.exportSession.outputFileType = AVFileTypeQuickTimeMovie;
CMTime start = CMTimeMakeWithSeconds(self.startTime, anAsset.duration.timescale);
CMTime duration = CMTimeMakeWithSeconds(self.stopTime-self.startTime, anAsset.duration.timescale);
CMTimeRange range = CMTimeRangeMake(start, duration);
self.exportSession.timeRange = range;
self.trimBtn.hidden = YES;
self.myActivityIndicator.hidden = NO;
[self.myActivityIndicator startAnimating];
[self.exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([self.exportSession status]) {
case AVAssetExportSessionStatusFailed:
NSLog(#"Export failed: %#", [[self.exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(#"Export canceled");
break;
default:
NSLog(#"NONE");
dispatch_async(dispatch_get_main_queue(), ^{
[self.myActivityIndicator stopAnimating];
self.myActivityIndicator.hidden = YES;
self.trimBtn.hidden = NO;
[self playMovie:self.tmpVideoPath];
});
break;
}
}];
}
}
without the changing frame rate and bit rate, it works perfectly.
Please give me any advise.
Thanks.
Framerate I'm still looking for, but bitrate has been solved by this drop in replacement for AVAssetExportSession: https://github.com/rs/SDAVAssetExportSession
Not sure but some things to look at. Unfortunatley the error messages dont tell you much in these cases in AVFoundation.
In general, I would make things simple and slowly add functionality.To start, make sure all layers start at zero and then end at the final duration. Do the same for the main composition. Invalid times may give you an error like this. For your instruction, make sure that it starts at the same time and ends at the same time too.

How to limit NSNumberFormatterCurrencyStyle

I have this in my code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *currency = [defaults objectForKey:#"currencySymbol"];
NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
text = [text stringByReplacingOccurrencesOfString:#"." withString:#""];
text = [text stringByReplacingOccurrencesOfString:currencySymbol withString:#""];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
[numberFormatter setCurrencySymbol:currency];
NSNumber *number = [NSNumber numberWithDouble:[text intValue]*0.01];
text = [numberFormatter stringFromNumber:number];
textField.text = text;
and it works great until you reach a certain amount, then it can't go higher, for example:
2,500.00 (is possible)
25,000.00 (it´s not possible)
Maybe it´s something stupid, could anyone alert me what is that i am not seeing?
Thanks.
For those who are having the same problem, we have to add this line of code:
text = [text stringByReplacingOccurrencesOfString:#"," withString:#""];
Because (logically) the , is used for thousands...

OCMock is only effective once, strange, why? Or what's wrong on my side?

I want to do mock for TnSettings, yes, it works if code by the following method, the problem is that we need to do write mock code for each case, if we only mock once then execute more than one case, then the second will report exception. I use the latest OCMock V2.01.
My question is that why OCMock has such restriction? Or is it my fault not to use it correctly?
Any idea or discussion will be appreciated, thanks in advance.
- (void) testFormattedDistanceValueWithMeters {
mockSettings = [OCMockObject mockForClass:[TnSettings class]];
mockClientModel = [TnClientModel createMockClientModel];
[[[mockClientModel expect] andReturn:mockSettings] settings];
[[[mockSettings expect] andReturn:[NSNumber numberWithInt:0]] preferencesGeneralUnits];
NSNumber *meters = [NSNumber numberWithDouble:0.9];
distance = [NSString formattedDistanceValueWithMeters:meters];
STAssertEqualObjects(distance, #"0.9", #"testformattedEndTimeForTimeInSeconds failed");
//------------- Another case -----------------
mockSettings = [OCMockObject mockForClass:[TnSettings class]];
mockClientModel = [TnClientModel createMockClientModel];
[[[mockClientModel expect] andReturn:mockSettings] settings];
[[[mockSettings expect] andReturn:[NSNumber numberWithInt:0]] preferencesGeneralUnits];
meters = [NSNumber numberWithDouble:100.9];
distance = [NSString formattedDistanceValueWithMeters:meters];
STAssertEqualObjects(distance, #"101", #"testformattedEndTimeForTimeInSeconds failed");
}
Not sure I understand your question or your code fully. I suspect that you stumbled over the difference between expect and stub, though.
Is this what you had in mind?
- (void) testFormattedDistanceValueWithMeters {
mockSettings = [OCMockObject mockForClass:[TnSettings class]];
mockClientModel = [TnClientModel createMockClientModel];
[[[mockClientModel stub] andReturn:mockSettings] settings];
[[[mockSettings stub] andReturn:[NSNumber numberWithInt:0]] preferencesGeneralUnits];
NSNumber *meters = [NSNumber numberWithDouble:0.9];
distance = [NSString formattedDistanceValueWithMeters:meters];
STAssertEqualObjects(distance, #"0.9", #"testformattedEndTimeForTimeInSeconds failed");
meters = [NSNumber numberWithDouble:100.9];
distance = [NSString formattedDistanceValueWithMeters:meters];
STAssertEqualObjects(distance, #"101", #"testformattedEndTimeForTimeInSeconds failed");
}

Trim file extension UITableView

I want to trim the file extension from text I have an NSMutableArray in table cells.
NSMutableArray *theFiles = [NSMutableArray new];
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager directoryContentsAtPath:#"/Test"];
for (NSString *s in fileList){
[theFiles addObject:fileList];
}
cell.textLabel.text = theFiles[indexPath.row];
return cell;
This lists for example "Xylophone.m4r" I want to remove the .m4r.
Try -[NSString stringByDeletingPathExtension] (in NSPathUtilities.h).
Actually, for my use, I was able to create a plist programmatically and just not use an extension and it works great! However, anothe rway to do this is:
[string stringByReplacingOccurrencesOfString:#".fileextension" withString:#""];
Just have to delete path extension component:
cell.textLabel.text = [[theFiles objectAtIndex:indexPath.row] stringByDeletingPathExtension];

Resources