I'm trying to create 9 text files on my Desktop which are named by variable i in the for loop. Inside each text file I want to write a long value determined by my bigInt function. The long value must then be written in the file 1000 times before moving on to the next text file. But I keep getting the error: Incompatible pointer types sending 'NSString*' to parameter of type 'NSData*'
My Function:
long bigInt(int i){
long big = 99*(i*99);
long evenBigger = big*(big*(big*big));
return evenBigger;
}
My main method:
long use;
int x = 0;
for (int i = 1; i<10; i++) {
while (x < 1000) {
use = bigInt(i);
//[NSString stringWithFormat:#"%ld", use];
//NSString *content = #"Text to write to file";
NSString *path = [NSString stringWithFormat: # "/Users/ou_snaaksie/Desktop/%i.txt", i];
//NSData *fileContents = [use dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager] createFileAtPath:path contents:[NSString stringWithFormat:#"%ld", use] attributes:nil];
x++;
}
}
I think you need to pass NSData instead of NSString object to contents in createFileAtPath:contents:attributes: method or you can do something like below:
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
}
[[string dataUsingEncoding:NSUTF8StringEncoding] writeToFile:path atomically:YES];
You are passing a string as contents when it requires NSData. You have to convert the string to NSData. Try this in the body of your while loop:
use = bigInt(i);
NSString* str = [NSString stringWithFormat:#"%ld", use];
NSData* data_contents = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *path = [NSString stringWithFormat: # "/tmp/%i.txt", i];
[data_contents writeToFile:path atomically:YES];
x++;
Related
The following code works perfectly to convert the NSData that I got from a URL/JSON file to a NSString, EXCEPTION MADE by the cases that data contains line breaks!
What's wrong with my code?
My Code:
NSError *errorColetar = nil;
NSURL *aColetarUrl = [[NSURL alloc]initWithString:#"http://marcosdegni.com.br/petsistema/teste/aColetar3.php"];
NSString *aColetarString = [NSString stringWithContentsOfURL:aColetarUrl encoding:NSUTF8StringEncoding error:&errorColetar];
NSLog(#"NSString: %#", aColetarString);
if (!errorColetar) {
NSData *aColetarData = [aColetarString dataUsingEncoding:NSUTF8StringEncoding];
self.arrayAColetar = [NSJSONSerialization JSONObjectWithData:aColetarData options:kNilOptions error:nil];
}
NSLog(#"arrayAColetar %#", self.arrayAColetar);
Log Results:
**NSString**: [{"id_atendimento":"2","observacoes":"ABC-Enter-->
DEF-Enter-->
GFH-END"},{"id_atendimento":"1","observacoes":"123Enter-->
345Enter-->
678End"}]
**arrayAColetar** (null)
As you can see my bottom line is an empty array :(
Thanks in advance!
By checking the error message hidden under 'error:nil' I found a "Unescaped control character around character" issue and implemented the code below from Unescaped control characters in NSJSONSerialization
and got a new 'cleaned' string.
- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString {
NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
if (range.location != NSNotFound) {
NSMutableString *mutable = [NSMutableString stringWithString:inputString];
while (range.location != NSNotFound) {
[mutable deleteCharactersInRange:range];
range = [mutable rangeOfCharacterFromSet:controlChars];
}
return mutable;
}
return inputString;
}
I would like to merge the two directories listings (already done and works they show up in NSTableView), but also display the contents of the files in an NSScrollview, now the problem lies in iterating through the list, and I couldn't figure out how I would come about that problem, I tried different techniques.
For now I get: "-[NSTextView replaceCharactersInRange:withString:]: nil NSString given.", probably because the iteration code is incorrect...
NSInteger row = [logsTableView selectedRow];
NSString *path1 = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Logs/"];
NSString *path2 = #"/Library/Logs/";
NSArray *directoryList1 = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path1 error:nil]
pathsMatchingExtensions:[NSArray arrayWithObjects:#"log", nil]];
NSArray *directoryList2 = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path2 error:nil]
pathsMatchingExtensions:[NSArray arrayWithObjects:#"log", nil]];
NSMutableArray *directoryList = [NSMutableArray array];
[directoryList addObjectsFromArray:directoryList1];
[directoryList addObjectsFromArray:directoryList2];
for (NSUInteger i = 0; i < directoryList.count; i++)
{
if (row == i)
{
for (NSUInteger i = 0; i < directoryList1.count; i++)
{
NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:#"Library/Logs/%#", [directoryList objectAtIndex:i]];
NSString *content = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:NULL];
[logsScrollViewTextView setString:content];
}
for (NSUInteger i = directoryList.count - directoryList1.count; i < directoryList.count; i++)
{
NSString *filePath = #[#"/Library/Logs/%#", [directoryList objectAtIndex:i]];
NSString *content = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:NULL];
[logsScrollViewTextView setString:content];
}
}
}
You don't need to iterate. All you need to do is to check which array the file name came from.
Assuming you aren't sorting the list, this is if (row >= directoryList1.count). This check tells you which list it came from so you can set the prefix.
If you are sorting and the names are unique you could use [directoryList1 containsObject:...).
With this code I determine the file size if the checkbox is NSOnState, but with a folder value is always 0. The directory is correct.
Can you help me?
unsigned long long resultsize=0;
if(imagehistoryS.state == NSOnState) {
NSString *path = [NSString stringWithFormat:#"Users/Giovanni/Desktop/test", [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
NSNumber *fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] objectForKey:NSFileSize];
resultsize += [fileSize doubleValue];
}
[result setStringValue:[NSString stringWithFormat:#"Total size items selected: %f", resultsize]];
You're passing in a string, and yet specifying the NSUserDomainMask. I've tried this and it works.
NSUInteger resultSize = 0;
NSFileManager *fm = [[NSFileManager alloc] init];
NSURL *LibraryURL = [[fm URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *previewsURL = [LibraryURL URLByAppendingPathComponent:#"/Caches/com.apple.Safari/Webpage Previews"];
resultSize = [[[fm attributesOfItemAtPath:[previewsURL path] error:nil] objectForKey:NSFileSize] unsignedIntegerValue];
NSLog(#"Size: %lu", resultSize);
This is for an ARC environment.
Note, I'm using NSURLs instead of NSString filepaths as much as possible. Also, you don't need to hardcode the user's name in the search path.
Updated to show the specific folder as requested in the comments
In you stringWithFormat you are missing the format specifier %#.
I need to write several line to a file. How can I move to the next line so that the file content is not overwritten each time? I am using a for loop with the following code in it
[anNSString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
The NSString. anNSString is reinitialized during each loop. SO i need to keep adding to the file path each during each loop.
Thanks
I feel like the accepted answer is not correct since it didn't answer the original question. To solve the original question you should use an NSOutputStream it makes appending content to an existing file an easy task:
NSString *myString = #"Text to append!"; // don't forget to add linebreaks if needed (\r\n)
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:YES];
[stream open];
NSData *strData = [myString dataUsingEncoding:NSUTF8StringEncoding];
[stream write:(uint8_t *)[strData bytes] maxLength:[strData length]];
[stream close];
You just write it out all at once, rather than attempting to write it incrementally. -[NSString writeToFile:atomically:encoding:error] will just overwrite the file each time - it does not append.
Here's an illustration:
NSMutableString * str = [NSMutableString new];
// > anNSString is reinitialized during each loop.
for ( expr ) {
NSString * anNSString = ...;
// > SO i need to keep adding to the file path each during each loop.
[str appendString:anNSString];
}
NSError * outError(0);
BOOL success = [str writeToFile:path
atomically:YES
encoding:NSUTF8StringEncoding
error:&outError];
[str release];
...
If you need to write to a new line each time, start with what is in #justin's answer, but add [str appendString:#"\r\n"]; wherever you need new lines.
NSMutableString * str = [NSMutableString new];
// > anNSString is reinitialized during each loop.
for ( expr ) {
NSString * anNSString = ...;
// > SO i need to keep adding to the file path each during each loop.
[str appendString:anNSString];
[str appendString:#"\r\n"]; //****** THIS IS THE NEW LINE ******
}
NSError * outError(0);
BOOL success = [str writeToFile:path
atomically:YES
encoding:NSUTF8StringEncoding
error:&outError];
[str release];
...
With this code, each anNSString will be on it's own line in the text file.
I am fetching result by fire a transaction but by the transaction one result is coming as blob attributes, that is image, I want to change that blob attribute to image
I wrote code for that "icon" is the key for fetch the image from transaction,
so please help me check this,
image is printing nil,
why?
NSString *inputString = [[[self formModel] attributeAsString:#"icon"] description];
NSLog(#"icon is %#",[[self formModel] attributeAsString:#"icon"]);
NSLog(#"inputstring is %#",inputString);
//NSImage *image = [NSUnarchiver unarchiveObjectWithData:[[self formModel] attributeAsString:#"icon"]];
//NSLog(#"image is %#",image);
NSArray *words = [inputString componentsSeparatedByString:#" "];
NSLog(#"words is %#",words);
NSArray *sizes = [words valueForKey:#"length"];
int sizeOfBytes = 0;
for (NSNumber *size in sizes) {
sizeOfBytes += [size intValue]/2;
}
int bytes[sizeOfBytes];
int counts = 0;
for (NSString *word in words) {
// convert each word from string to int
NSMutableString *ostr = [NSMutableString stringWithCapacity:[word length]];
while ([word length] > 0) {
[ostr appendFormat:#"%#", [word substringFromIndex:[word length] - 2]];
word = [word substringToIndex:[word length] - 2];
}
NSScanner *scaner = [NSScanner scannerWithString:ostr];
unsigned int val;
[scaner scanHexInt:&val];
bytes[counts] = val;
counts++;
}
// get NSData form c array
NSData *data = [NSData dataWithBytes:bytes length:sizeOfBytes];
NSLog(#"My NSDATA %#",data);
NSImage *Image = [[NSImage alloc] initWithData:data];
Never use the output of description to do processing. There is no guarantee of its format. What format is your original "blob" in and how was it generated? Your code suggests it might be an NSData or it might be an NSKeyArchiver. Both of these easily convert to NSData. You never need to do this by hand by converting to a string.