No visible #interface for 'NSFileManager' declares the selector 'moveItemAtPath:toPath:' - objective-c

I'm trying to use the moveItemAtPath method, but I am getting an error about using an interface.
> #import <Cocoa/Cocoa.h>
>
> int main(int argc, const char * argv[]) {
> #autoreleasepool {
> NSFileManager *manage = [NSFileManager defaultManager];
> NSString *a = #"folder1/file.txt";
> NSString *b = #"folder2/file.txt";
> NSString *path = [NSHomeDirectory() stringByAppendingFormat:#"/%#", a];
> NSString *newPath = [NSHomeDirectory() stringByAppendingFormat:#"/%#", b];
>
> [manage moveItemAtPath:path toPath:newPath];
> }
> return NSApplicationMain(argc, argv); }
I don't get how looking at the UIViewController , as explained in here https://stackoverflow.com/a/12696856 is supposed to help.
This resource does not show an example of what needs to be imported https://www.techotopia.com/index.php/Working_with_Files_in_Objective-C#Moving.2FRenaming_a_File

Related

Objective-C Categories: Method not called

I'm trying to learn the basics of Objective-C through reading "Learning Objective-C 2.0" Theres an exercise on categories where your asked to add a method to NSString through use of categories. My simple program is below. it (should) take a string and then reverses the order of the words.
Main
#import <Foundation/Foundation.h>
#import "CatNSString.h"
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSString *test = #"Dog bites Man";
NSString *test1 = nil;
test1 = [test1 reverseWords: test];
NSLog(#"%# : %#", test, test1);
}
return 0;
}
Interface
#import <Foundation/Foundation.h>
#interface NSString (CatNSString)
- (NSString*) reverseWords:(NSString*)string;
#end
Implementation
#import "CatNSString.h"
#implementation NSString (CatNSString)
- (NSString*) reverseWords: (NSString*) string
{
NSString *stringReturn = nil;
NSArray *arrayString = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
stringReturn = [string stringByAppendingString:#"hello"];
for (NSString *word in arrayString)
{
NSString *stringTmp1 = word;
NSString *stringTmp2 = stringReturn;
stringReturn = [stringTmp1 stringByAppendingString:stringTmp2];
NSLog(#"stringTmp1: %#", stringTmp1);
}
return stringReturn;
}
#end
It compiles but the program acts as though the method is never called. If I place a NSLog call in the method there is no output to the console. Can anyone see what I'm not doing that I should be doing?
You just did it wrong way.
Here is the proper way to define a Category:
#interface NSString (CatNSString)
-(NSString *)reverse;
#end
#implementation NSString (CatNSString)
-(NSString*)reverse {
// `Self` keyword will refer to your original string, no need to pass it as a parameter
NSArray *words = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
return [[[words reverseObjectEnumerator] allObjects] componentsJoinedByString:#" "];
}
#end
And in your main code, do the following:
NSString *test = #"Dog bites Man";
NSLog(#"%#", [test reverse]);

SQLite Problems when using NSFileManager

I am using SQLite and previous answers state that I should use this code:
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrayOfPerson;
sqlite3 *personDB;
NSString *dbPathString;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
arrayOfPerson = [[NSMutableArray alloc]init];
[[self myTableView]setDelegate:self];
[[self myTableView]setDataSource:self];
[self createOrOpenDB];
}
- (void)createOrOpenDB
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
dbPathString = [docPath stringByAppendingPathComponent:#"persons.db"];
char *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:dbPathString];
NSLog(#"here 0");
if (!success) {// THIS IS MY CONCERN
const char *dbPath = [dbPathString UTF8String];
NSLog(#"here 1");
//creat db here
NSLog(#"sqlite3 = %d",sqlite3_open(dbPath, &personDB));
NSLog(#"OK= %d", SQLITE_OK);
if (sqlite3_open(dbPath, &personDB)==SQLITE_OK) {
NSLog(#"here 2");
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS PERSONS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE INTEGER)";
sqlite3_exec(personDB, sql_stmt, NULL, NULL, &error);
sqlite3_close(personDB);
}
}
}
However, when I run this code my app does not gets into this loop:
if(!success) {
....
}
I tried using
if(success) {
....
}
and it works. But I do not think that is correct. Please help me.

Can't move a file in objective c

I'm a beginner in this language.
I want to move a file from one folder to another my code is here.
The console give me file exists at path twice
And the moveItemAtPath gives me always false
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSString * originPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Downloads/1.wav"];
NSString * finalPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Desktop"];
NSFileManager * manager = [[NSFileManager alloc]init];
if( [ manager fileExistsAtPath:originPath]){
NSLog(#"The file exists at: %#",originPath);
}
if( [manager fileExistsAtPath:finalPath]){
NSLog(#"The file exists at: %#",finalPath);
}
if([manager moveItemAtPath:originPath toPath:finalPath error:nil]){
NSLog(#"True");
}else{
NSLog(#"FALSE");
}
}
return 0;
}
First of all you should use [NSFileManager defaultManager] instead of creating a new NSFileManager. It will return a singleton-instance of NSFileManager.
Add this to your second "ifFileExists"-check:
[[NSFileManager defaultManager] removeItemAtPath:finalPath error:nil];
This will remove the item at the target-path, before moving a new one to this destination.

How to get all tracks from an album using iTunes.h/Scripting Bridge

I'd like to get all tracks from an album on iTunes using iTunes.h.
Right now I get the data of the current track by:
NSInteger trackID = iTunes.currentTrack.databaseID;
NSString *name = iTunes.currentTrack.name;
And the name of the album by:
NSString *trackAlbum = iTunes.currentTrack.album;
But know I don't know how to get all the tracks that are in the same album as the current track.
Any ideas? Thanks
The iTunes API is poorly written.
You have to filter the array with a predicate.
NSArray *allSongs = [self allSongs];
NSArray *songsOfAlbum = [allSongs filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"album == %# && artist == %#", albumString, artistString]];
You can get all the songs like this:
// Get all Songs
- (NSArray *)allSongs {
if (_allSongs == nil) {
NSArray *tracksToPlay = [(SBElementArray *)[self.library tracks] get];
// Sort by artist
_allSongs = tracksToPlay;
}
return _allSongs;
}
- (iTunesLibraryPlaylist *)library {
if (_library == nil) {
// Whole Library
iTunesSource *source = [[[[self.iTunes sources] get] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"kind == %i", iTunesESrcLibrary]] objectAtIndex:0];
// Only the Music
_library = [[[[source playlists] get] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"specialKind == %i", iTunesESpKMusic]] objectAtIndex:0];
}
return _library;
}
You can use iTunes Library Framework (10.9 osx) for iTunes 11.
#import <iTunesLibrary/ITLibrary.h>
#import <iTunesLibrary/ITLibMediaItem.h>
#import <iTunesLibrary/ITLibAlbum.h>
NSError *error = nil;
ITLibrary *library = [ITLibrary libraryWithAPIVersion:#"1.0" error:&error];
if (library)
{
NSArray *tracks = library.allMediaItems; // <- NSArray of ITLibMediaItem
}
for (ITLibMediaItem *item in tracks) {
NSLog(#"tracks %#",item.album.title);
}
You can fetch album information from ITLibMediaItem
As an example to retrieve the artworks I have submitted a github repository:
It is an objective c code which uses the above code changed:
#import <Foundation/Foundation.h>
#import <iTunesLibrary/ITLibrary.h>
#import <iTunesLibrary/ITLibMediaItem.h>
#import <iTunesLibrary/ITLibArtwork.h>
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSError *error = nil;
ITLibrary *library = [ITLibrary libraryWithAPIVersion:#"1.0" error:&error];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (library)
{
//NSArray *playlists = library.allPlaylists; // <- NSArray of ITLibPlaylist
NSArray *tracks = library.allMediaItems; // <- NSArray of ITLibMediaItem
[tracks enumerateObjectsUsingBlock:^(ITLibMediaItem* _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (obj.artworkAvailable) {
ITLibArtwork* artWork=obj.artwork;
//NSData* d=artWork.imageData;
switch (artWork.imageDataFormat) {
case ITLibArtworkFormatPNG:{
NSURL* fileURL=obj.location;
NSString* fs=fileURL.lastPathComponent;
NSString* path=[fileURL.path stringByReplacingOccurrencesOfString:fs withString:#"Folder.png"];
if (![fileManager fileExistsAtPath:path]){
[artWork.imageData writeToFile:path atomically:YES];
}
}
break;
case ITLibArtworkFormatJPEG:{
NSURL* fileURL=obj.location;
NSString* fs=fileURL.lastPathComponent;
NSString* path=[fileURL.path stringByReplacingOccurrencesOfString:fs withString:#"Folder.jpg"];
if (![fileManager fileExistsAtPath:path]){
[artWork.imageData writeToFile:path atomically:YES];
}
}
break;
default:
break;
}
}
}];
NSLog(#"End reached");
}
}
return 0;
}
https://github.com/ENees/iTunesGetImages

how to collect system info in osx using objective c

Is there any method / API defined to collect system info in osx.
I want to write utility which will collect hardware information like CPU,RAM,Network adapter.
Any idea ?
Thanks in advance.
System Profiler is nice and will output an XML for some slow file I/O and also let's depend on another process to complete before getting the desired information. Well if I put it this way, is System Profiler really the best option and answer for this question? I think not (IMO).
Here is how I do it. The header are readonly properties of the private readwrite properties. The category methods are pretty straight forward, but if anyone has a question then post and I will answer.
#import <IOKit/IOKitLib.h>
#import <sys/sysctl.h>
#interface VarSystemInfo ()
#property (readwrite, strong, nonatomic) NSString *sysName;
#property (readwrite, strong, nonatomic) NSString *sysUserName;
#property (readwrite, strong, nonatomic) NSString *sysFullUserName;
#property (readwrite, strong, nonatomic) NSString *sysOSName;
#property (readwrite, strong, nonatomic) NSString *sysOSVersion;
#property (readwrite, strong, nonatomic) NSString *sysPhysicalMemory;
#property (readwrite, strong, nonatomic) NSString *sysSerialNumber;
#property (readwrite, strong, nonatomic) NSString *sysUUID;
#property (readwrite, strong, nonatomic) NSString *sysModelID;
#property (readwrite, strong, nonatomic) NSString *sysModelName;
#property (readwrite, strong, nonatomic) NSString *sysProcessorName;
#property (readwrite, strong, nonatomic) NSString *sysProcessorSpeed;
#property (readwrite, strong, nonatomic) NSNumber *sysProcessorCount;
#property (readonly, strong, nonatomic) NSString *getOSVersionInfo;
- (NSString *) _strIORegistryEntry:(NSString *)registryKey;
- (NSString *) _strControlEntry:(NSString *)ctlKey;
- (NSNumber *) _numControlEntry:(NSString *)ctlKey;
- (NSString *) _modelNameFromID:(NSString *)modelID;
- (NSString *) _parseBrandName:(NSString *)brandName;
#end
static NSString* const kVarSysInfoVersionFormat = #"%#.%#.%# (%#)";
static NSString* const kVarSysInfoPlatformExpert = #"IOPlatformExpertDevice";
static NSString* const kVarSysInfoKeyOSVersion = #"kern.osrelease";
static NSString* const kVarSysInfoKeyOSBuild = #"kern.osversion";
static NSString* const kVarSysInfoKeyModel = #"hw.model";
static NSString* const kVarSysInfoKeyCPUCount = #"hw.physicalcpu";
static NSString* const kVarSysInfoKeyCPUFreq = #"hw.cpufrequency";
static NSString* const kVarSysInfoKeyCPUBrand = #"machdep.cpu.brand_string";
static NSString* const kVarSysInfoMachineNames = #"MachineNames";
static NSString* const kVarSysInfoMachineiMac = #"iMac";
static NSString* const kVarSysInfoMachineMacmini = #"Mac mini";
static NSString* const kVarSysInfoMachineMacBookAir = #"MacBook Air";
static NSString* const kVarSysInfoMachineMacBookPro = #"MacBook Pro";
static NSString* const kVarSysInfoMachineMacPro = #"Mac Pro";
#pragma mark - Implementation:
#pragma mark -
#implementation VarSystemInfo
#synthesize sysName, sysUserName, sysFullUserName;
#synthesize sysOSName, sysOSVersion;
#synthesize sysPhysicalMemory;
#synthesize sysSerialNumber, sysUUID;
#synthesize sysModelID, sysModelName;
#synthesize sysProcessorName, sysProcessorSpeed, sysProcessorCount;
#pragma mark - Helper Methods:
- (NSString *) _strIORegistryEntry:(NSString *)registryKey {
NSString *retString;
io_service_t service =
IOServiceGetMatchingService( kIOMasterPortDefault,
IOServiceMatching([kVarSysInfoPlatformExpert UTF8String]) );
if ( service ) {
CFTypeRef cfRefString =
IORegistryEntryCreateCFProperty( service,
(__bridge CFStringRef)registryKey,
kCFAllocatorDefault, kNilOptions );
if ( cfRefString ) {
retString = [NSString stringWithString:(__bridge NSString *)cfRefString];
CFRelease(cfRefString);
} IOObjectRelease( service );
} return retString;
}
- (NSString *) _strControlEntry:(NSString *)ctlKey {
size_t size = 0;
if ( sysctlbyname([ctlKey UTF8String], NULL, &size, NULL, 0) == -1 ) return nil;
char *machine = calloc( 1, size );
sysctlbyname([ctlKey UTF8String], machine, &size, NULL, 0);
NSString *ctlValue = [NSString stringWithCString:machine encoding:[NSString defaultCStringEncoding]];
free(machine); return ctlValue;
}
- (NSNumber *) _numControlEntry:(NSString *)ctlKey {
size_t size = sizeof( uint64_t ); uint64_t ctlValue = 0;
if ( sysctlbyname([ctlKey UTF8String], &ctlValue, &size, NULL, 0) == -1 ) return nil;
return [NSNumber numberWithUnsignedLongLong:ctlValue];
}
- (NSString *) _modelNameFromID:(NSString *)modelID {
/*!
* #discussion Maintain Machine Names plist from the following site
* #abstract ref: http://www.everymac.com/systems/by_capability/mac-specs-by-machine-model-machine-id.html
*
* #discussion Also info found in SPMachineTypes.plist # /System/Library/PrivateFrameworks/...
* ...AppleSystemInfo.framework/Versions/A/Resources
* Information here is private and can not be linked into the code.
*/
NSDictionary *modelDict = [[NSBundle mainBundle] URLForResource:kVarSysInfoMachineNames withExtension:#"plist"].serialPList;
NSString *modelName = [modelDict objectForKey:modelID];
if ( !modelName ) {
if ( [modelID.lowercaseString hasPrefix:kVarSysInfoMachineiMac.lowercaseString] ) return kVarSysInfoMachineiMac;
else if ( [modelID.lowercaseString hasPrefix:kVarSysInfoMachineMacmini.noWhitespaceAndLowerCaseString] ) return kVarSysInfoMachineMacmini;
else if ( [modelID.lowercaseString hasPrefix:kVarSysInfoMachineMacBookAir.noWhitespaceAndLowerCaseString] ) return kVarSysInfoMachineMacBookAir;
else if ( [modelID.lowercaseString hasPrefix:kVarSysInfoMachineMacBookPro.noWhitespaceAndLowerCaseString] ) return kVarSysInfoMachineMacBookPro;
else if ( [modelID.lowercaseString hasPrefix:kVarSysInfoMachineMacPro.noWhitespaceAndLowerCaseString] ) return kVarSysInfoMachineMacPro;
else return modelID;
} return modelName;
}
- (NSString *) _parseBrandName:(NSString *)brandName {
if ( !brandName ) return nil;
NSMutableArray *newWords = [NSMutableArray array];
NSString *strCopyRight = #"r", *strTradeMark = #"tm", *strCPU = #"CPU";
NSArray *words = [brandName componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];
for ( NSString *word in words ) {
if ( [word isEqualToString:strCPU] ) break;
if ( [word isEqualToString:#""] ) continue;
if ( [word.lowercaseString isEqualToString:strCopyRight] ) continue;
if ( [word.lowercaseString isEqualToString:strTradeMark] ) continue;
if ( [word length] > 0 ) {
NSString *firstChar = [word substringToIndex:1];
if ( NSNotFound != [firstChar rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location ) continue;
[newWords addObject:word];
} } return [newWords componentsJoinedByString:#" "];
}
- (NSString *) getOSVersionInfo {
NSString *darwinVer = [self _strControlEntry:kVarSysInfoKeyOSVersion];
NSString *buildNo = [self _strControlEntry:kVarSysInfoKeyOSBuild];
if ( !darwinVer || !buildNo ) return nil;
NSString *majorVer = #"10", *minorVer = #"x", *bugFix = #"x";
NSArray *darwinChunks = [darwinVer componentsSeparatedByCharactersInSet:[NSCharacterSet punctuationCharacterSet]];
if ( [darwinChunks count] > 0 ) {
NSInteger firstChunk = [(NSString *)[darwinChunks objectAtIndex:0] integerValue];
minorVer = [NSString stringWithFormat:#"%ld", (firstChunk - 4)];
bugFix = [darwinChunks objectAtIndex:1];
return [NSString stringWithFormat:kVarSysInfoVersionFormat, majorVer, minorVer, bugFix, buildNo];
} return nil;
}
#pragma mark - Initalization:
- (void) setupSystemInformation {
NSProcessInfo *pi = [NSProcessInfo processInfo];
self.sysName = [[NSHost currentHost] localizedName];
self.sysUserName = NSUserName();
self.sysFullUserName = NSFullUserName();
self.sysOSName = pi.strOperatingSystem;
self.sysOSVersion = self.getOSVersionInfo;
self.sysPhysicalMemory = [[NSNumber numberWithUnsignedLongLong:pi.physicalMemory] strBinarySizeMaxFractionDigits:0];
self.sysSerialNumber = [self _strIORegistryEntry:(__bridge NSString *)CFSTR(kIOPlatformSerialNumberKey)];
self.sysUUID = [self _strIORegistryEntry:(__bridge NSString *)CFSTR(kIOPlatformUUIDKey)];
self.sysModelID = [self _strControlEntry:kVarSysInfoKeyModel];
self.sysModelName = [self _modelNameFromID:self.sysModelID];
self.sysProcessorName = [self _parseBrandName:[self _strControlEntry:kVarSysInfoKeyCPUBrand]];
self.sysProcessorSpeed = [[self _numControlEntry:kVarSysInfoKeyCPUFreq] strBaseTenSpeedMaxFractionDigits:2];
self.sysProcessorCount = [self _numControlEntry:kVarSysInfoKeyCPUCount];
}
- (id) init {
if ( (self = [super init]) ) {
[self setupSystemInformation];
} return self;
}
#end
Enjoy!
P.S. I load all the property values during init so as to avoid multiple system calls && because its cheap && all values should be fairly static.
P.P.S. I also load a MachineNames plist that I created, but I know its my own process only that has access to it and the comment describes where I get the information.
The easiest way is to use the output from the system_profiler command. It also has an -xml option to make the output easy to automatically parse.
The underlying API that I believe System Profiler uses (for at least some of the information it gathers), and that you should use if you want very specific information, is sysctl. It lets you query for individual attributes of the system, including number of CPUs, CPU speed, available RAM, etc.
You can use the scripting bridge in Leopard (or newer) to get the information you want directly from Apple System Profiler.