I've done the following to allocate buffers for OpenAL in Swift:
init() {
self.buffers = NSMutableArray(capacity: 2);
self.sources = NSMutableArray(capacity: 2);
var sources: [ALuint] = [ALuint](count: 2, repeatedValue: 0);
var buffers: [ALuint] = [ALuint](count: 2, repeatedValue: 0);
alGenSources(2, UnsafeMutablePointer<ALuint>(sources));
alGenBuffers(2, UnsafeMutablePointer<ALuint>(buffers));
for i in 0...2 {
self.sources.addObject(NSNumber(unsignedInt: sources[i]));
self.buffers.addObject(NSNumber(unsignedInt: buffers[i]));
}
}
And it works perfectly fine. I cannot figure out how to delete it though. I tried:
deinit {
for i in 0...2 {
var source = self.sources.objectAtIndex(i).unsignedIntValue;
var buffer = self.buffers.objectAtIndex(i).unsignedIntValue;
//Error below.. I can't get address of "source" or "buffer".
alDeleteSources(1, UnsafePointer<ALuint>(ALuint(source)));
}
self.sources = nil; //cannot nil an NSMutableArray either..
self.buffers = nil;
}
So how can I get the address of the source and buffer variables to pass it to the UnsafePointer<ALuint>?
I'm trying to translate my Objective-C code below to the Swift code above:
-(void) init
{
if (!_sources)
{
unsigned int sources[2];
unsigned int buffers[2];
alGenSources(2, &sources[0]);
alGenBuffers(2, &buffers[0]);
_sources = [[NSMutableArray alloc] initWithCapacity: 2];
_buffers = [[NSMutableArray alloc] initWithCapacity: 2];
for (int i = 0; i < 2; ++i)
{
[_sources addObject: [NSNumber numberWithUnsignedInt: sources[i]]];
[_buffers addObject: [NSNumber numberWithUnsignedInt: buffers[i]]];
}
}
}
-(void) dealloc
{
for (int i = 0; i < [_sources count]; ++i)
{
unsigned int source = [[_sources objectAtIndex: i] unsignedIntValue];
unsigned int buffer = [[_buffers objectAtIndex: i] unsignedIntValue];
alDeleteSources(1, &source);
alDeleteBuffers(1, &buffer);
}
_sources = nil;
_buffers = nil;
}
I think you can simply use Array like:
class FuBar {
var sources = [ALuint](count: 2, repeatedValue: 0);
var buffers = [ALuint](count: 2, repeatedValue: 0);
init() {
alGenSources(2, &sources)
alGenBuffers(2, &buffers)
}
deinit {
alDeleteSources(2, &sources)
alDeleteBuffers(2, &buffers)
}
}
You don't have to use UnsafeMutablePointer explicitly, because in-out(&) expression of Array for UnsafeMutablePointer<T> is automatically converted to the pointer of the first element of the buffer of the array. see the docs.
Related
I want to create creepify text in my app with js code (creepify())
https://github.com/combatwombat/Lunicode.js/blob/master/lunicode.js
website using this js code: http://lunicode.com/creepify
My problem is when i try to combine characters, the result is'nt like in website.
I try to create 3 NSMutableArray
NSMutableArray *diacriticsTop;
NSMutableArray *diacriticsMiddle;
NSMutableArray *diacriticsBottom;
and store value like this
for (int i = 768; i <= 789; i++) {
[diacriticsTop addObject:[NSNumber numberWithInt:i]];
}
for (int i = 790; i <= 819; i++) {
if (i != 794 && i != 795) {
[diacriticsBottom addObject:[NSNumber numberWithInt:i]];
}
}
...
then i convert creepify() in js code to
- (NSString *)creepifyString:(NSString *)inputString
{
BOOL isTop = YES;
BOOL isMiddle = YES;
BOOL isBottom = YES;
NSInteger maxHeight = 15;
NSInteger randomization = 100;
NSMutableString *outputString = [[NSMutableString alloc] init];
unichar output = 0;
for (int i = 0; i < inputString.length; i++) {
unichar c = [inputString characterAtIndex:i];
if (isMiddle) {
NSNumber *temp = diacriticsMiddle[lroundf(drand48()*diacriticsMiddle.count)];
c = c + (unichar) temp;
}
// Top
if (isTop) {
// Put up to this.options.maxHeight random diacritics on top.
// optionally fluctuate the number via the randomization value (0-100%)
// randomization 100%: 0 to maxHeight
// 30%: 70% of maxHeight to maxHeight
// x%: 100-x% of maxHeight to maxHeight
int diacriticsTopLength = diacriticsTop.count - 1;
for (int count = 0,
len = maxHeight - drand48()*((randomization/100)*maxHeight); count < len; count++) {
NSNumber *temp = diacriticsTop[lroundf(drand48()*diacriticsTopLength)];
c = c + (unichar) temp;
}
}
// Bottom
if (isBottom) {
int diacriticsBottomLength = diacriticsBottom.count - 1;
for (int count = 0,
len = maxHeight - drand48()*((randomization/100)*maxHeight); count < len; count++) {
NSNumber *temp =diacriticsBottom[lroundf(drand48()*diacriticsBottomLength)];
c = c + (unichar) temp;
}
}
output = output + c;
}
[outputString appendFormat:#"%C", output];
NSLog(#"%#", outputString);
return outputString;
}
I call class_copyPropertyList in my function
+ (NSDictionary *)classPropsFor:(Class)klass{
if (klass == NULL) {
return nil;
}
NSMutableDictionary *results = [[NSMutableDictionary alloc] init] ;
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(klass, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *propName = property_getName(property);
if(propName) {
const char *propType = getPropertyType(property);
NSString *propertyName = [NSString stringWithUTF8String:propName];
NSString *propertyType = [NSString stringWithUTF8String:propType];
if (propertyType != nil){
[results setObject:propertyType forKey:propertyName];
}
}
}
free(properties);
// returning a copy here to make sure the dictionary is immutable
return [NSDictionary dictionaryWithDictionary:results];
}
But for example class with 2 properties it's get different count of properties list: one time 0 count, else time 2, else time 1.
Why?
This is happening on iOS 7
One task of my program is to scan local wi-fi network for any devices/computers in same network. I found solution to get all working devices IPs, but did not managed to get names of them. I did not find any clue to solve this problem.
Any suggestions?
In order to perform a reverse DNS lookup, you need to call the CFHostGetNames function, like this:
+ (NSArray *)hostnamesForIPv4Address:(NSString *)address
{
struct addrinfo *result = NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_NUMERICHOST;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
int errorStatus = getaddrinfo([address cStringUsingEncoding:NSASCIIStringEncoding], NULL, &hints, &result);
if (errorStatus != 0) {
return nil;
}
CFDataRef addressRef = CFDataCreate(NULL, (UInt8 *)result->ai_addr, result->ai_addrlen);
if (addressRef == nil) {
return nil;
}
freeaddrinfo(result);
CFHostRef hostRef = CFHostCreateWithAddress(kCFAllocatorDefault, addressRef);
if (hostRef == nil) {
return nil;
}
CFRelease(addressRef);
BOOL succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL);
if (!succeeded) {
return nil;
}
NSMutableArray *hostnames = [NSMutableArray array];
CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
for (int currentIndex = 0; currentIndex < [(__bridge NSArray *)hostnamesRef count]; currentIndex++) {
[hostnames addObject:[(__bridge NSArray *)hostnamesRef objectAtIndex:currentIndex]];
}
return hostnames;
}
BOOL succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL); Now I encounter that always failed at this line, and I tried to use getnameinfo function, it is still can't get the hostname
I am trying this code for generating a random number and saving the list of numbers in an array, then i am trying to delete those numbers from the list one by one which appeared once, e.g
1, 5, 9 , 4, 3, 7 ,6 ,10, 11, 8, 2 are the list of integers now 9 is appeared once and now i do not need 9 again.. this is my code of random non repeating numbers array.
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
BOOL record = NO;
int x;
for (int i=0; [storeArray count] < 10; i++) //Loop for generate different random values
{
x = arc4random() % 10;//generating random number
if(i==0)//for first time
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
else
{
for (int j=0; j<= [storeArray count]-1; j++)
{
if (x ==[[storeArray objectAtIndex:j] intValue])
record = YES;
}
if (record == YES)
{
record = NO;
}
else
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
}
}
Try this,
NSArray *arrRandoms = [[NSArray alloc]initWithObjects:1,5,8,7,36,17,96,32,5,7,8,13,36,nil] ; // This contains your random numbers
NSMutableArray *arrFresh = [[NSMutableArray alloc]init];
// Now removing the duplicate numbers
BOOL checkRepeat = NO;
int _Current;
for (int i=0; i<[arrRandoms count]; i++)
{
_Current = [arrRandoms objectAtIndex:i];
if (i == 0)
[arrFresh addObjects:_Current];
else
{
checkRepeat = NO;
for(int j=0; j< [arrFresh count]; j++)
{
if ( _Current == [arrFresh objectAtIndex:j])
checkRepeat = YES;
}
if (checkRepeat == NO)
[arrFresh addObjects:_Current];
}
}
I think this code will work. Check It.
try it
//**************remove repeat objects from array***************************//
NSArray *noDuplicates = [[NSSet setWithArray: yourArray] allObjects];
you add
.h file
BOOL isSame;
NSMutableArray *countArray;
NSInteger randomNumber;
.m file
countArray=[[NSMutableArray alloc]init];
//get randon no
-(NSInteger)getRandomNo:(NSInteger)range
{
isSame=TRUE;
while (isSame){
isSame = FALSE;
randomNumber = arc4random() % range;
for (NSNumber *number in countArray){
if([number intValue] ==randomNumber){
isSame = TRUE;
break;
}
}
}
[countArray addObject:[NSNumber numberWithInt:randomNumber]];
return randomNumber;
}
Tested Please try this,
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
NSMutableSet * setUnique = [[NSMutableSet alloc] init];
for (int i=0; [setUnique count] < 10; i++) //Loop for generate different random values
{
[setUnique addObject:[NSNumber numberWithInt:arc4random() % 10]];
}
storeArray = [[setUnique allObjects] mutableCopy];
// check this how to get random number in array (i.e.. this array(below arr_numbers) contain non repeated number)
// for general purpose i am posting this.. so people cannot check for another answer
int num_count = 10;
int RandomNumber;
NSMutableArray *arr_numbers = [[NSMutableArray alloc] init];
for (int j =0; j < num_count; j++)
{
RandomNumber = 0 + arc4random() % num_count;
NSLog(#"%d",RandomNumber);
if ([arr_numbers count]>0)
{
if (![arr_numbers containsObject:[NSNumber numberWithInt:RandomNumber]])//
{
[arr_numbers addObject:[NSNumber numberWithInt:RandomNumber]];
}
if (j == num_count-1)
{
if ([arr_numbers count] != num_count)
{
j = 0;
}
}
}
else
{
[arr_numbers addObject:[NSNumber numberWithInt:RandomNumber]];
}
}
NSLog(#"%#",arr_numbers);
I wrote a custom file type that data from my Java program gets saved to. I want to get the data out on an iPod/Pad/Phone. So far I wrote this file for reading strait byte values from a file and changing them into NSStrings and integers.
#import "BinaryFileReader.h"
#implementation BinaryFileReader
- (id)init {
self = [super init];
return self;
}
- (id)initWithLocation:(NSString*)filepath {
if ((self = [super init])) {
_file = [NSFileHandle fileHandleForReadingAtPath:filepath];
_fileOffset = 0;
if (_file == nil)
NSLog(#"%#%#",#"Failed to open file at path:",filepath);
}
return self;
}
- (void)close {
[_file closeFile];
}
- (int)readInt {
[_file seekToFileOffset:_fileOffset];
_databuffer = [_file readDataOfLength:4];
_fileOffset+=4;
return (int)[_databuffer bytes];
}
- (NSString*)readNSString {
int length = [self readInt];
[_file seekToFileOffset:_fileOffset];
_databuffer = [_file readDataOfLength:length];
_fileOffset+=length;
return [[NSString alloc] initWithData:_databuffer encoding:NSUTF8StringEncoding];
}
- (NSMutableArray*)readNSMutableArrayOfNSString {
NSMutableArray* array = [[NSMutableArray alloc] init];
int arrayLength = [self readInt];
int length;
for (int i=0; i<arrayLength; i++) {
length = [self readInt];
[_file seekToFileOffset:_fileOffset];
_databuffer = [_file readDataOfLength:length];
_fileOffset+=length;
[array addObject:[[NSString alloc] initWithData:_databuffer encoding:NSUTF8StringEncoding]];
}
return array;
}
#end
Now when I try to use this to read NSStrings or integers it does not come up with the right values. I assume since both NSStrings and integers are coming up wrong it's something in the readInt method. Anyone see something glaringly obvious that I've missed here?
Edit:
The file format that I am trying to read starts with a string. That string, when read with readNSString, is the correct string but the first 1/3 of the string is missing.
Java code:
public void saveItem() {
try {
byte[] bytes;
FileOutputStream output;
if (countOccurrences(location.getPath(),'.')==1) {
System.out.println("Option 1");
output = new FileOutputStream(location+"/"+name+".dtb");
} else {
output = new FileOutputStream(location);
}
bytes = name.getBytes("UTF-8");
output.write(bytes.length);
output.write(bytes);
output.write(otherNames.length);
for (int i=0;i<otherNames.length;i++) {
bytes = otherNames[i].getBytes("UTF-8");
output.write(bytes.length);
output.write(bytes);
}
bytes = description.getBytes("UTF-8");
output.write(bytes.length);
output.write(bytes);
bytes = XactCode.getBytes("UTF-8");
output.write(bytes.length);
output.write(bytes);
bytes = SymbilityCode.getBytes("UTF-8");
output.write(bytes.length);
output.write(bytes);
output.write(averageLowPrice);
output.write(averageHighPrice);
output.write(averageLifeExpectancy);
output.close();
bytes = null;
} catch (Exception e) {
e.printStackTrace();
}
}
The reason this does not work is the way you are casting the NSData to int. The bytes methods returns a pointer to the actual data, which you will need to deference to get the actual value (otherwise you will just be getting the memory address of the pointer).
I tried two ways:
int test = 64;
NSData *data = [NSData dataWithBytes:&test length:4];
int test2 = (int)[data bytes]; //This gave me 170382992
and
int test = 64;
NSData *data = [NSData dataWithBytes:&test length:4];
int test2 = *((int *)[data bytes]); //This gave me 64